我有3个模型(Allen, Bob, Chris),它们与Join模型是多态的。和一个连接到join模型的User模型。
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
我认为,没有标准的方法来实现这一点。在您的Allen
, Bob
和Chris
中添加after_create
回调,您将获得与此特定Bob
相关的所有User
的列表,并手动重新计算bobs_count
。