Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby on rails after_remove, after_add callbacks on has_many :through

I have a model which fits the following pattern:

class foo < ActiveRecord::Base

  has_many :bar, :dependent => :destroy

  has_many :baz, :through => :bar, :uniq => true,
    :after_add => :update_baz_count,
    :after_remove => :update_baz_count

  def update_baz_count(record)
    debugger
    # stuff...
  end
end

I am try to maintain a count of unique baz's associated with foo through bar. But for some reason, the after_add and after_remove callbacks are never called when I add a bar (which has to have a baz) to foo. Any ideas why? I have used these callbacks with habtm and they work fine.

Thanks.

like image 229
deruse Avatar asked Jun 06 '11 07:06

deruse


2 Answers

Notice that after_destroy callbacks will not be triggered on the associated entity when using has_many :through

From rails documentation:

If the :through option is true callbacks in the join models are triggered except destroy callbacks, since deletion is direct.

You should stick to the add/remove callbacks, just make sure you declare the association only once.

like image 94
nimast Avatar answered Nov 05 '22 09:11

nimast


It's not working because you're making a bar association and that doesn't have the callbacks added. I would do this with after_create and after_destroy methods in the bar class. That way they will trigger whichever possible way you make the association.

#in Bar class
after_create :update_foo_baz_count
after_destroy :update_foo_baz_count

def update_foo_baz_count
  self.foo.update_baz_count
end
like image 5
Max Williams Avatar answered Nov 05 '22 09:11

Max Williams