Monday, January 14, 2013

The not so famous before_remove/before_add & after_remove/after_add callbacks.

Well, this is another rails feature and a quite nice one which is not documented properly.

While using has_many :through associations, we can use before_remove, before_add, after_remove, after_add callbacks.


We can pass methods to these callbacks which would be called when a new association is added or removed.

The fun part here is, the after/before_remove callback works even when #delete method is called on an object. How about that!!

So, if you have an association like:

..............................................................................................................................................

class Foo < ActiveRecord::Base

.......

has_many :bars, :through => foo_bars, :after_remove => :remove_deleted_foo_bars

-----

def remove_deleted_foo_bars(record)   <---- This parameter has to be passed
   //perform action
end
...................................................................................................................................................

Also, should any of the before_add callbacks throw an exception, the object does not get added to the collection. Same with the before_remove callbacks; if an exception is thrown the object doesn’t get removed. <---- This is from the rails docs ;)

In my case, i had to expire cache when the association was deleted, so this came in really handy to me. Hope this helps you all :)

3 comments:

  1. Seems that this works with has_and_belongs_to_many associations (which is kinda same of has_many :through anyway).

    Great methods, pity they're not quite well documented, thanks for the post!

    ReplyDelete
  2. Yeah, some important things are really very poorly documented in Rails.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete