Mongoid 3.1.0 CounterCache不起作用

编程入门 行业动态 更新时间:2024-10-28 05:21:36
本文介绍了Mongoid 3.1.0 CounterCache不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

本文发布于:2023-11-22 19:01:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618625.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不起作用   Mongoid   CounterCache

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!