【问题标题】:Issues with has_many :through, cache, touch and counter_cachehas_many 的问题:through、cache、touch 和 counter_cache
【发布时间】:2011-04-01 16:49:22
【问题描述】:

我的应用中有很多 has_many :through 关系。我正在扩展显示与此相关的信息,例如连接对象的数量。每当用户更新关系时,连接表都会被修改,我可以捕捉到我的 Sweepers。

问题是,连接表条目被删除,而不是销毁。如果关系消失了,我就没有合理的方法来检测这一点,并且我正在从缓存中显示误导性信息。像 :touch => true 或 :counter_cache => true 这样的所有东西都可以部分工作。如果更新或创建关系,它会增加。但是,如果用户删除关系,则不会发生任何事情。 :counter_cache 坏了, :touch 没有触发。

垃圾解决方案是在保存主模型时在控制器中调用.touch。这种作品,但看起来真的很不专业。这应该在模型逻辑中,而不是在控制器中。

我觉得我错过了一些重要的东西,但我无法理解这一点。任何人都可以对这个问题提出一些见解?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord has-many-through


    【解决方案1】:

    查看 Mark S. 为回答他自己的问题而写的猴子补丁:How to create a full Audit log in Rails for every table?

    ActiveRecord::Associations::HasManyThroughAssociation.class_eval do 
      def delete_records(records)
        klass = @reflection.through_reflection.klass
        records.each do |associate|
          klass.destroy_all(construct_join_attributes(associate))
        end
      end
    end
    

    它也可能对您的问题有用。请注意,这是在 Rails 2 中。如果您已经在使用 Rails 3,情况可能会有所不同。

    【讨论】:

      【解决方案2】:

      猴子修补 Active Record 不是必需的。定义关联时,将:dependent 选项设置为:destroy

      class Book < ActiveRecord::Base
        has_many :authorships, :dependent => :destroy
        has_many :authors, :through => :authorships, :dependent => :destroy
      end
      

      【讨论】:

      • 如果你只想要加入模型的回调(authorships),你只需要在关联模型上添加dependent: :destroyauthors
      猜你喜欢
      • 2010-12-22
      • 2014-10-06
      • 1970-01-01
      • 1970-01-01
      • 2011-02-11
      • 1970-01-01
      • 2011-11-06
      • 2019-03-04
      • 2023-03-07
      相关资源
      最近更新 更多