检测现有ActiveRecord关联的更改

Ven*_* D. 0 ruby activerecord ruby-on-rails

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

chr*_*pes 5

您可以简单地覆盖关联的setter.这也可以让您更自由地了解更改,例如在更改Eg之前和之后使用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
Run Code Online (Sandbox Code Playgroud)

这也适用于批量分配.