如何在一个模型中触发多个counter_cache为has_many:through

时间:2011-11-09 12:32:26

标签: ruby-on-rails ruby activerecord counter-cache

我有3个模型(Allen,Bob,Chris),它们是Join模型的多态。以及与连接模型连接的用户模型。

class Allen < ActiveRecord::Base
  has_many :joins, :as => :resource
  ...
end

class Bob < ActiveRecord::Base
  has_many :joins, :as => :resource
  ...
end

class Chris < ActiveRecord::Base
  has_many :joins, :as => :resource 
  ...
end

class Join < ActiveRecord::Base
  belongs_to :initiator, :class_name => "User", :foreign_key => "user_id"
             :counter_cache => "How to write with 3 different counter cache?"

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

class User < ActiveRecord::Base
  has_many :joins
  has_many :allens, :through => :joins, :source => :initiator

  has_many :initial_joins, :class_name => "Join"
end

我的问题是如何在用户模型中为Bob,Chris和Allen编写计数器缓存

或者您可以在此处查看:https://gist.github.com/1350922

1 个答案:

答案 0 :(得分:0)

我认为,没有标准的方法来实现这一目标。向after_createAllenBob添加Chris回调,您可以在其中获取与此特定User相关联的所有Bob的列表并手动重新计算每个bobs_count