0

アソシエーションがいつ変更されるかを知る必要があるActiveRecord拡張機能を書いています。通常、:after_addおよび:after_removeコールバックを使用できることは知っていますが、関連付けがすでに宣言されている場合はどうなりますか?

4

2 に答える 2

5

関連付けのセッターを単純に上書きできます。これにより、変更をより自由に見つけることができます。たとえば、変更の前後に関連オブジェクトがあります。

class User < ActiveRecord::Base
  has_many :articles

  def articles= new_array
    old_array = self.articles
    super new_array
    # here you also could compare both arrays to find out about what changed
    # e.g. old_array - new_array would yield articles which have been removed
    #   or new_array - old_array would give you the articles added 
  end
end

これは、大量割り当てでも機能します。

于 2013-03-20T16:48:03.883 に答える
3

あなたが言うようにafter_addafter_removeコールバックを使用できます。さらにafter_commit、関連付けモデルのフィルターを設定し、変更について「親」に通知します。

class User < ActiveRecord::Base
  has_many :articles, :after_add => :read, :after_remove => :read     

  def read(article)
    # ;-)
  end
end 

class Article < ActiveRecord::Base
  belongs_to :user

  after_commit { user.read(self) }
end
于 2012-09-28T19:37:58.573 に答える