2

我正在尝试使用 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 

关于这个问题的任何想法?

4

1 回答 1

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

如果有人有更简单或更清洁的方法来做到这一点,那就太棒了。

于 2013-03-05T19:24:08.723 回答