【问题标题】:ruby on rails after_remove, after_add callbacks on has_many :throughruby on rails after_remove,has_many 上的 after_add 回调:通过
【发布时间】:2011-09-09 01:58:42
【问题描述】:

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

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 一起使用,它们工作正常。

谢谢。

【问题讨论】:

    标签: ruby-on-rails model callback has-many-through


    【解决方案1】:

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

    来自 Rails 文档:

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

    你应该坚持添加/删除回调,只要确保你只声明一次关联。

    【讨论】:

      【解决方案2】:

      它不起作用,因为您正在创建条形关联并且没有添加回调。我会在 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-17
        • 2012-06-12
        • 2012-06-20
        • 1970-01-01
        • 1970-01-01
        • 2012-01-14
        • 2010-12-28
        • 1970-01-01
        相关资源
        最近更新 更多