gpt4 book ai didi

ruby-on-rails - has_many :through, 缓存、touch 和 counter_cache 的问题

转载 作者:数据小太阳 更新时间:2023-10-29 07:38:39 26 4
gpt4 key购买 nike

我的应用程序中有很多 has_many :through 关系。我 extensivley 显示与此相关的信息,例如连接对象的数量。每当用户更新关系时,连接表都会被修改,我可以捕获这个我的清道夫。

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

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

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

最佳答案

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

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

关于ruby-on-rails - has_many :through, 缓存、touch 和 counter_cache 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3531795/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com