Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/amazon-web-services/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
ruby-on-rails在删除之后,在添加回调之后有很多:通过_Ruby On Rails_Model_Callback_Has Many Through - Fatal编程技术网

ruby-on-rails在删除之后,在添加回调之后有很多:通过

ruby-on-rails在删除之后,在添加回调之后有很多:通过,ruby-on-rails,model,callback,has-many-through,Ruby On Rails,Model,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_

我有一个符合以下模式的模型:

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
class foo:destroy
有很多:baz,:through=>:bar,:uniq=>true,
:在添加=>之后:更新添加计数,
:删除后=>:更新\u baz\u计数
def更新_baz_计数(记录)
调试器
#东西。。。
结束
结束
我试图通过酒吧保持与foo相关的独特baz的数量。但是由于某些原因,当我向foo添加一个bar(必须有一个baz)时,after_add和after_remove回调永远不会被调用。你知道为什么吗?我已经将这些回调用于habtm,它们工作得很好


谢谢。

它不起作用,因为你正在建立一个律师协会,而且没有添加回调。我将使用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

请注意,当使用
has\u many:to

来自rails文档:

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

您应该坚持使用add/remove回调,只需确保只声明一次关联即可