【问题标题】:Rails Counter Cache and its implementationRails 计数器缓存及其实现
【发布时间】:2010-03-19 09:31:39
【问题描述】:

我正在尝试获取 Rails 计数器缓存功能,但无法完全掌握它。

假设我们有 3 个模型

A B C

A 属于 B 或 C,具体取决于字段 key_type 和 key_id。 key_type 告诉 A 属于 B 还是 C,因此如果 key_type="B" 则记录属于 B,否则属于 C。

在我的模型 a.rb 中,我定义了以下关联:

belongs_to :b, :counter_cache => true, :foreign_key => "key_id"
belongs_to :c, :counter_cache => true, :foreign_key => "key_id"

在 b 和 c 模型文件中

has_many :as , :conditions => {:key_type => "B"}
has_many :as , :conditions => {:key_type => "C"}

B 和 C 模型都有一个 as_count 列

问题是每次创建 a 的对象时,模型 b 和 c 中的计数都会增加。

感谢任何帮助。最初我认为这可能有效:

belongs_to :b, :counter_cache => true, :foreign_key => "key_id", :conditions => {:key_type => "B"}
belongs_to :c, :counter_cache => true, :foreign_key => "key_id", :conditions => {:key_type => "C"}

但这无济于事。

谢谢

【问题讨论】:

  • 这不应被标记为“grails”。

标签: ruby-on-rails ruby ruby-on-rails-plugins


【解决方案1】:

看起来多态关联是解决您的问题的方法。

假设您有一个 Comment 模型和 2 个可以评论的模型:Post 和 Profile。

在 Post 和 Profile 模型中:

has_many :comments, :as => :resource

在评论模型中:

belongs_to :resource, :polymorphic => true, :counter_cache => true

不要忘记在 Profile 和 Post 模型中添加“cmets_count”列,瞧!

【讨论】:

  • 仅在添加 cmets 时有效。 cmets_count 增加,但删除评论时不会更新 cmets_count。知道为什么会发生这种情况吗?任何可能的解决方案?谢谢。
  • 看起来在 rails github.com/rails/rails/issues/16407
【解决方案2】:
猜你喜欢
  • 2017-10-26
  • 1970-01-01
  • 2019-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-21
相关资源
最近更新 更多