Mongoid 3.1.0 CounterCache doesn't work

青春壹個敷衍的年華 提交于 2019-12-10 22:29:56

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/14691272/mongoid-3-1-0-countercache-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!