ruby on rails after_remove,after_add回调on_many:through

der*_*use 6 model ruby-on-rails callback 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
Run Code Online (Sandbox Code Playgroud)

我试图通过bar保持与foo相关的唯一baz的数量.但由于某种原因,当我向foo添加一个bar(必须有一个baz)时,永远不会调用after_add和after_remove回调.有什么想法吗?我已将这些回调与habtm一起使用,并且它们工作正常.

谢谢.

nim*_*ast 6

请注意,使用after_destroy时不会在关联实体上触发回调has_many :through

来自rails文档:

如果:through选项为true,则会触发连接模型中的回调,但销毁回调除外,因为删除是直接的.

您应该坚持添加/删除回调,只需确保只声明一次关联.


Max*_*ams 5

它不起作用,因为你正在建立一个条形关联,并且没有添加回调.我会使用bar类中的after_create和after_destroy方法执行此操作.这样,它们将触发您进行关联的任何可能方式.

#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
Run Code Online (Sandbox Code Playgroud)