【问题标题】:Mongoid 3.1.0 CounterCache doesn't workMongoid 3.1.0 CounterCache 不起作用
【发布时间】:2013-02-04 16:43:26
【问题描述】:

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

对这个问题有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails mongoid counter-cache


    【解决方案1】:

    我遇到了同样的事情。这对我有用。

    假设您的应用中已经有这些类,并且您决定稍后添加 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
    

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

    【讨论】:

    • 它有效。但是每次我初始化一个新孩子时我都必须这样做吗?因为没有它似乎无法工作。还是我有两个父母的问题?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多