2010-03-19 66 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