我有一个适合以下模式的模型:
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
我试图通过bar来保持与foo相关的唯一baz的计数。但是由于某种原因,当我在foo中添加一个bar(必须有一个baz)时,永远不会调用after_add和after_remove回调。有什么想法吗?我已经将这些回调与habtm一起使用,并且它们可以正常工作。
谢谢。
最佳答案
请注意,使用after_destroy
时,关联实体上不会触发has_many :through
回调
从Rails文档中:
If the :through option is true callbacks in the join models are triggered except destroy callbacks, since deletion is direct.
您应该坚持添加/删除回调,只需确保仅声明一次关联即可。
关于ruby-on-rails - ruby on has_many :through上的after_remove,after_add回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6248846/