0

I have 3 models(Allen, Bob, Chris) which are polymorphic with Join model. and a User model which connect with the join model.

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

My question is how to write the counter cache for Bob, Chris and Allen in User Model

or you can review it here: https://gist.github.com/1350922

chenillen
  • 1
  • 1

1 Answers1

0

I think, there's no standard way to achieve this. Add an after_create callback to your Allen, Bob and Chris where you would get the list of all Users associated with this particular Bob and recalculate bobs_count for each of them manually.

RocketR
  • 3,626
  • 2
  • 25
  • 38