Rails 3 has_many changed?

glebm picture glebm · Feb 21, 2012 · Viewed 8.9k times · Source

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

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.

The question is, what is the best way to do it for has_many attributes?

Answer

ka8725 picture ka8725 · Feb 21, 2012

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)

See Ryan Bates's railscast for more information: #109 episode

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

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.