0

サブスクリプションを取得して製品で更新できず、製品の属性をサブスクリプションテーブルと同じフィールドに複製できません。

私のアソシエーションはで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

次に、複製しようとしているのと同じ列を持つProductandテーブル: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を想定していることは次のとおりです。

  1. 特定の製品のサブスクリプションが存在するかどうか、および存在するかどうかを確認してください。
  2. 製品の新しい編集済み属性を使用して、現在のユーザーサブスクリプションを更新します。

現在、サブスクリプションは製品が更新されても更新されません。これを行うには、このコードについて何を修正する必要がありますか?製品フィールドをサブスクリプションに複製する場合はどうですか?

4

2 に答える 2

1

それが単なるタイプミスかどうかはわかりませんが、オブザーバーは間違っています。selfオブザーバーではあなたの製品ではありません。product代わりに、(指定されたパラメーター)を代わりに使用する必要があります。

第二に、サブスクリプションの検索も間違っているようです。あなたが使用subscribable_idsubscribable_typeている、そして定義されていない、したがってただnilproduct.idとを使用したいと思います'Product'が、製品のすべてのサブスクリプションを繰り返すことができます。その製品にリンクされているproduct.subscriptionsすべてを返します。subscriptions

price最後に、サブスクリプションをリンクされた製品と常に同期させ続ける場合はname、代わりに次のようなことをしないでください。

 create_table :products do |t|
   t.string  :name
   t.decimal :price
   t.integer :user_id
end

create_table :subscriptions do |t|
   t.integer :subscriber_id # same as user_id
   t.integer :subscribable_id
   t.string  :subscribable_type
end

サブスクリプションモデル内で

class Subscription
  belongs_to :subscriber, :class_name => "User"
  belongs_to :subscribable, :polymorphic => true

  delegate :name, :price, :to => :subscribable, :allow_nil => true
end

お役に立てれば。

于 2012-04-11T20:47:47.950 に答える
0

:autosave => trueアソシエーションオプションに渡してみてください。

あなたはここでそれについてもっと読むことができます。

于 2012-04-09T05:56:29.237 に答える