0

我正在编写一个 ActiveRecord 扩展,它需要知道何时修改关联。我知道通常我可以使用 :after_add 和 :after_remove 回调,但是如果关联已经声明了怎么办?

4

2 回答 2

5

您可以简单地覆盖关联的设置器。这也将让您更自由地了解更改,例如在更改之前和之后拥有 assoc 对象。

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 回答