サブスクリプションを取得して製品で更新できず、製品の属性をサブスクリプションテーブルと同じフィールドに複製できません。
私のアソシエーションはでsubscriptions
あり、にproducts
属していますUser
が、aProduct
には多くのがありsubscriptions
ます。
Subscription.rb
class Subscription
belongs_to :subscriber, :class_name => "User"
belongs_to :subscribable, :polymorphic => true
end
Product.rb
class Product
belongs_to :user
has_many :subscriptions, :as => :subscribable, :dependent => :destroy
end
User.rb
class User
has_many :products, :dependent => :destroy
has_many :subscriptions, :foreign_key => :subscriber_id, :dependent => :destroy
end
次に、複製しようとしているのと同じ列を持つProduct
andテーブル:Subscription
create_table :products do |t|
t.string :name
t.decimal :price
t.integer :user_id
end
create_table :subscriptions do |t|
t.string :name
t.decimal :price
t.integer :subscriber_id # same as user_id
t.integer :subscribable_id
t.string :subscribable_type
end
ProductsController
def edit
@product = Product.find(params[:id])
end
def update
@product = Product.find(params[:id])
if @product.update_attributes(params[:product])
redirect_to(@product, :notice => 'Successfully Updated.')
else
render :back
end
end
ProductObserver
class ProductObserver < ActiveRecord::Observer
def after_update(product)
if self.subscriptions.find_by_subscribable_id_and_subscribable_type(subscribable_id, subscribable_type)
subscription = Subscription.find_by_subscribable_id_and_subscribable_type(subscribable_id, subscribable_type)
self.subscription.update_attributes(params[:subscription]).select{ |key, _| Subscription.attribute_names.include? key })
end
end
end
行うことafter_update
を想定していることは次のとおりです。
- 特定の製品のサブスクリプションが存在するかどうか、および存在するかどうかを確認してください。
- 製品の新しい編集済み属性を使用して、現在のユーザーサブスクリプションを更新します。
現在、サブスクリプションは製品が更新されても更新されません。これを行うには、このコードについて何を修正する必要がありますか?製品フィールドをサブスクリプションに複製する場合はどうですか?