ruby on Rails after_remove、after_add 上的 has_many 回调:through
我有一个符合以下模式的模型:
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 一起使用,它们工作得很好。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请注意,使用
has_many :through
时,不会在关联实体上触发after_destroy
回调。来自 Rails 文档:
您应该坚持添加/删除回调,只需确保仅声明一次关联即可。
Notice that
after_destroy
callbacks will not be triggered on the associated entity when usinghas_many :through
From rails documentation:
You should stick to the add/remove callbacks, just make sure you declare the association only once.
它不起作用,因为您正在建立一个酒吧协会并且没有添加回调。我将使用 bar 类中的 after_create 和 after_destroy 方法来执行此操作。这样它们就会触发您以任何可能的方式建立关联。
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.