Mongoid 3.1.0 CounterCache不起作用 [英] Mongoid 3.1.0 CounterCache doesn't work
问题描述
我正在尝试使用Mongoid CounterCache,但是它不起作用.
I'm trying to use Mongoid CounterCache but it doesn't work.
我尝试只使用
belongs_to :user, counter_cache: true
但是它返回
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.
所以我加了
include Mongoid::CounterCache
重新启动我的网络服务器,然后再试一次,但它返回
Restarted my webserver then tried again, but it returns
uninitialized constant Mongoid::CounterCache
关于这个问题有什么想法吗?
Any ideas about this problem?
推荐答案
我遇到了同样的问题.这是对我有用的东西.
I ran into this same thing. Here's what worked for me.
假设您的应用程序中已经有这些类,然后您决定稍后添加counter_cache.因此,您将counter_cache: true
添加到您的子类中
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.
这篇关于Mongoid 3.1.0 CounterCache不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!