ruby-on-rails – Rails Counter Cache及其实现

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails Counter Cache及其实现前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图抓住rails counter cache功能但不能完全掌握它.

假设我们有3个型号

A B C.

A取决于字段key_type和key_id,属于B或C. 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,: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中都会增加count.

任何帮助表示赞赏.最初我认为这可行:

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

但这没有用.

谢谢

解决方法

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

想象一下,你有一个评论模型和2个可以评论的模型:帖子和个人资料.

在Post和Profile模型中:

has_many :comments,:as => :resource

评论模型中:

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

不要忘记在Profile和Post模型中添加“comments_count”列并vo!

原文链接:https://www.f2er.com/ruby/267576.html

猜你在找的Ruby相关文章