2010-03-19 68 views
6

我试图抓住rails计数器缓存功能,但无法完全掌握它。Rails计数器缓存及其实现

比方说,我们有3种型号

A B C

A属于B或C,这取决于现场为key_type和KEY_ID。为key_type告诉A是否属于B或C因此,如果为key_type =“B”,则记录属于否则它属于C.

以我模型a.rb到B,我已经定义以下关联:

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"} 

但这没有帮助。

谢谢

+0

这不应该被标记为“grails”。 – Fletch 2010-12-03 11:32:03

回答

15

它看起来像多态关联是你的问题的方式去。

想象一下,你有一个评论模型和2个模型,可以评论:发布和配置文件。

在讯息和个人资料型号:

has_many :comments, :as => :resource 

在Comment模型:

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

不要忘记在这两个配置文件和Post模型就万事大吉了添加 “comments_count” 栏目!

+0

只有在添加评论时才起作用。 comments_count增加,但是当评论被删除时,它不会更新comments_count。任何想法为什么这可能会发生?任何可能的解谢谢。 – 2014-10-14 16:38:20

+0

看起来像在rails <5.0中有一个counter_cache和多态关系的bug。请参阅https://github.com/rails/rails/issues/16407 – John 2016-01-07 16:25:19