检测现有ActiveRecord关联的更改

时间:2012-09-28 15:37:18

标签: ruby-on-rails ruby activerecord

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

2 个答案:

答案 0 :(得分:5)

您可以简单地覆盖关联的setter。这也可以让您更自由地了解变化,例如:在变更之前和之后有关联对象。

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

这也适用于质量分配。

答案 1 :(得分: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