2

I'm trying to use Mongoid CounterCache but it doesn't work.

I tried to just use

belongs_to  :user, counter_cache: true

But it returns

Problem:
Invalid option :counter_cache provided to relation :user.

Summary:
Mongoid checks the options that are passed to the relation macros to ensure that no ill side effects occur by letting something slip by.

Resolution:
Valid options are: autobuild, autosave, dependent, foreign_key, index, polymorphic, touch, class_name, extend, inverse_class_name, inverse_of, name, relation, validate, make sure these are the ones you are using.

So then I added

include Mongoid::CounterCache

Restarted my webserver then tried again, but it returns

uninitialized constant Mongoid::CounterCache 

Any ideas about this problem?

Seif Sallam
  • 821
  • 2
  • 10
  • 30

1 Answers1

3

I ran into this same thing. Here's what worked for me.

Let's say you have these class already in your app, and you decided to add the counter_cache later. So you add the counter_cache: true to your child class

class User
    include Mongoid::Document
    field :name, type: String
    has_many :things
end

class Thing
    include Mongoid::Document
    field :name, type: String
    belongs_to :user, counter_cache: true
end

Then you hop into your console and do this:

u = User.first
u.things.count #=> 10
u.things_count #=> NoMethodError: undefined method things_count
User.update_counters(u.id, things_count: u.things.count)
u.reload
u.things_count #=> 10

If anyone has an easier or cleaner way to do this, that would be awesome.

jeremywoertink
  • 2,281
  • 1
  • 23
  • 29
  • 1
    It works. But do I have to do this every time i initialise a new child. Because it doesn't seem to work without it. Or is the problem that I have 2 parents? – Seif Sallam Mar 26 '13 at 08:31