我需要跟踪像这样设置的关联的更改(添加和删除):
has_many :listing_services
has_many :services, through: :listing_services
对于普通属性,最简单的方法是检查l.changes[attribute]
in before_save
or l.previous_changes[attribute]
in after_save
.
问题是,最好的方法是什么has_many
属性?
我没用过changes
方法。但我相信你总能使用魔法<attribute_name>_changed?
and <attribute_name>_was
:
services.any? {|s| s.attribute_name_changed?}
services.map(&:attribute_name_was)
请参阅瑞安·贝茨 (Ryan Bates) 铁路广播了解更多信息:第109章 第109章 http://railscasts.com/episodes/109-tracking-attribute-changes
UPDATE: 可以通过:after_delete
, and :after_add
回调到has_many
直接关联:
has_many :items, :after_add => :my_method_or_proc1, :after_remove => :my_method_or_proc2
请小心使用这些回调并注意它们的工作原理。他们
被召唤items.build
and items.create
once。所以如果你打电话items.build
然后保存父对象(带有嵌套属性
例子)after_add
打回来只会在构建时调用一次
关联对象。这意味着如果父级有验证则构建items
不会保存在数据库中,您不能依赖after_add
打回来。换句话说,它并没有说添加的关联的记录已保存在数据库中。因此您可以保证仅在调用时添加和保存项目items.create
。我希望你能理解这个澄清。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)