ruby-on-rails – Rails 3 has_many已更改?
发布时间:2020-12-16 22:46:57 所属栏目:百科 来源:网络整理
导读:我需要跟踪这样一个关联设置的更改(添加和删除): has_many :listing_serviceshas_many :services,through: :listing_services 对于普通属性,简单的方法是检查after_save中的l.changes [attribute]或after_save中的l.previous_changes [attribute]. 问题是,
我需要跟踪这样一个关联设置的更改(添加和删除):
has_many :listing_services has_many :services,through: :listing_services 对于普通属性,简单的方法是检查after_save中的l.changes [attribute]或after_save中的l.previous_changes [attribute]. 问题是,对于has_many属性,最好的方法是什么? 解决方法
我没有使用更改方法.但我确信你总是可以使用魔术方法< attribute_name> _changed?和< attribute_name> _was:
services.any? {|s| s.attribute_name_changed?} services.map(&:attribute_name_was) 有关更多信息,请参阅Ryan Bates的轨道车辆:#109 episode 更新:你可以传递:after_delete和:after_add回调到has_many关联直接: has_many :items,:after_add => :my_method_or_proc1,:after_remove => :my_method_or_proc2 使用这些回调,并注意它们如何工作.他们被调用在items.build和items.create一次.所以如果你打电话items.build然后保存父对象(具有嵌套属性示例)after_add回调将仅在构建时调用一次关联对象.这意味着如果父级有验证,则构建的项不会保存在数据库中,并且不能依赖于after_add回调.换句话说,它并不表示添加关联的记录保存在数据库中.所以你有保证项目被添加和只保存在call items.create.我希望你明白这个澄清. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |