1

I have some code here

class group < ActiveRecord::Base 
    has_many :memberships, :dependent => :destroy         
    has_many :members, :through => :memberships,  :source => :person
                       :conditions => ['memberships.pending = ? ', false]

     ......

now, I want add a counter_cache for members. Because of the conditions schema, I can't add counter_cache on memberships instead of members. But class person does not belong_to groups, it has_many memberships and memberships belong_to groups. Where should I add the :counter_cache schema ?

or how can I implememt the requirement : add a counter_cache for membership

Thx

Ye Ren
  • 11
  • 2

2 Answers2

0

Building on @Ramon Tayag's answer, a better way to implement your own counter cache when you have your own conditions would be to use the increment_counter method:

class Membership < ActiveRecord::Base
  after_create :increment_group_pending_counter_cache

  private

  def increment_group_pending_counter_cache
    if self.pending
      Group.increment_counter :pending_member_counter, group_id
    end
  end
end

Where Group is the model class that has a column named "pending_member_counter", and your Membership model has a group_id column that relates it to the Group model.

Full docs: http://apidock.com/rails/ActiveRecord/CounterCache/increment_counter

stereoscott
  • 13,309
  • 4
  • 33
  • 34
0

You probably should implement your own cache counter then.

class Membership < ActiveRecord::Base
  after_create :increment_group_pending_counter_cache

  private

  def increment_group_pending_counter_cache
    if self.pending
      # let's say the column in the groups table is called `pending_member_counter`
      self.group.update_attribute :pending_member_counter, group.pending_member_counter + 1
    end
  end
end

You should also create a counter cache for when a membership is destroyed. But I think I've typed in enough for you to implement that.

Ramon Tayag
  • 15,224
  • 9
  • 43
  • 69