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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With