我正在尝试使用Mongoid CounterCache,但它不起作用。
我试图使用
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
重新启动我的网络服务器,然后再次尝试,但它返回
uninitialized constant Mongoid::CounterCache
关于这个问题的任何想法?
答案 0 :(得分:3)
我遇到了同样的事情。这对我有用。
假设您已经在您的应用中使用了这些类,并且您决定稍后添加counter_cache。因此,您将counter_cache: true
添加到您的子类
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
然后你跳进你的控制台并执行此操作:
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
如果有人有更简单或更清洁的方法,那就太棒了。