Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a counter_cache be used with a has_many?

I'm working to add a counter_cache to my models:

Users (id, org_id) Orgs (id, users_count)

But get the following error: ArgumentError (Unknown key(s): counter_cache):

class Org < ActiveRecord::Base
   has_many :users, :counter_cache => true

class User < ActiveRecord::Base
   belongs_to :org

Any ideas what is setup wrong. I would like Org.users_count to return the counter_cache for the # of users in that org?

like image 456
AnApprentice Avatar asked Feb 22 '12 18:02

AnApprentice


1 Answers

It doesn't work this way. You have to move the counter_cache to the belongs_to:

class User < ActiveRecord::Base
   belongs_to :org, :counter_cache => true
end

And add a users_count field to the Org model and then Rails will update the field for you. Don't forget to add a :default=> 0 in the migration, otherwise it won't work fine.

If you have already some data in your app and you want to sync the counter, you can run (after the migration) something like the following:

  Org.find(:all).each do |o|
    Org.update_counters o.id, :users_count => o.users.count
  end
like image 66
lucapette Avatar answered Sep 24 '22 02:09

lucapette