0

Join モデルでポリモーフィックな 3 つのモデル (Allen、Bob、Chris) があります。結合モデルに接続する 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

私の質問は、ユーザー モデルでボブ、クリス、アレンのカウンター キャッシュを記述する方法です。

または、ここで確認できます: https://gist.github.com/1350922

4

1 に答える 1

0

これを達成するための標準的な方法はないと思います。after_createにコールバックを追加します。ここAllenBob、この特定のに関連付けられているChrisすべてののリストを取得し、それらのそれぞれについて手動で再計算します。UserBobbobs_count

于 2012-03-14T10:53:16.600 に答える