Rails Counter Cache及其实现

Ish*_*shu 6 ruby ruby-on-rails ruby-on-rails-plugins

我试图抓住rails counter cache功能但不能完全掌握它.

假设我们有3个型号

ABC

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, :counter_cache => true, :foreign_key => "key_id"
Run Code Online (Sandbox Code Playgroud)

在b和c模型文件中

has_many :as , :conditions => {:key_type => "B"}
has_many :as , :conditions => {:key_type => "C"}
Run Code Online (Sandbox Code Playgroud)

B和C模型都有一个as_count列

问题是每次创建a的对象时,在模型b和c中都会增加count.

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

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"}
Run Code Online (Sandbox Code Playgroud)

但这没有用.

谢谢

小智 15

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

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

在Post和Profile模型中:

has_many :comments, :as => :resource
Run Code Online (Sandbox Code Playgroud)

在评论模型中:

belongs_to :resource, :polymorphic => true, :counter_cache => true
Run Code Online (Sandbox Code Playgroud)

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