Rails 3 has_many改变了吗? [英] Rails 3 has_many changed?
问题描述
我需要跟踪这样设置的关联的更改(添加和删除):
I need to track changes (additions and deletes) of an association set up like this:
has_many :listing_services
has_many :services, through: :listing_services
对于普通属性,简便的方法是在 before_save
或 l.previous_changes [attribute]
l.changes [attribute] >在 after_save
中.
For normal attributes the easist way to do it is to check l.changes[attribute]
in before_save
or l.previous_changes[attribute]
in after_save
.
问题是,对 has_many
属性执行此操作的最佳方法是什么?
The question is, what is the best way to do it for has_many
attributes?
推荐答案
我没有使用 changes
方法.但我确定您总是可以使用魔术方法< attribute_name> _changed?
和< attribute_name> _was
:
I didn't use changes
method. But I'm sure that you always can use magic methods <attribute_name>_changed?
and <attribute_name>_was
:
services.any? {|s| s.attribute_name_changed?}
services.map(&:attribute_name_was)
有关更多信息,请参见Ryan Bates的railscast:#109集
See Ryan Bates's railscast for more information: #109 episode
更新:您可以将:after_delete
和:after_add
回调直接传递给 has_many
关联:>
UPDATE: You can pass :after_delete
, and :after_add
callbacks to has_many
association directly:
has_many :items, :after_add => :my_method_or_proc1, :after_remove => :my_method_or_proc2
请小心使用这些回调,并注意它们的工作方式.在 items.build
和 items.create
一次上调用.所以如果你打电话 items.build
,然后保存父对象(具有嵌套属性,用于示例) after_add
回调在构建时仅被调用一次关联对象.这意味着,如果父级进行了验证,则内置的 items
将不会保存在数据库中,并且您不能依赖 after_add
回调.换句话说,这并不是说添加的关联记录已保存在数据库中.因此,您可以确保仅在调用 items.create
时添加和保存该项目.希望您能理解这一点.
Be careful using these callbacks and pay attention how they work. They
are called on items.build
and items.create
once. So if you call
items.build
and then save parent object (with nested attributes for
example) after_add
callback will be called only once on building
associated object. It means that if parent has validation then built items
won't be saved in the database and you can't rely on after_add
callback. In other words it doesn't say that added association's record was saved in the DB. So you have guarantee that item is added and saved only on call items.create
. I hope you understand this clarification.
这篇关于Rails 3 has_many改变了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!