开发者

ruby on rails after_remove, after_add callbacks on has_many :through

开发者 https://www.devze.com 2023-03-10 21:10 出处:网络
I have a model which fits the following pattern: class foo < ActiveRecord::Base has_many :bar, :dependent => :destroy

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 th开发者_运维百科ey work fine.

Thanks.


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消