首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mongoid 3.1.6的未定义方法`reset_counters‘

Mongoid 3.1.6的未定义方法`reset_counters‘
EN

Stack Overflow用户
提问于 2015-02-20 08:40:26
回答 1查看 153关注 0票数 1

我刚刚将mongoid更新为3.1.6版本,以便可以使用计数器方法跟踪我的模型关系。但是,正如我在gem更新之前所做的那样,我仍然会得到以下错误:

代码语言:javascript
复制
undefined method `reset_counters' for Mongoid::Persistence::Atomic::Operation:Module

在我的Gemfile中,我有这样的版本:

代码语言:javascript
复制
gem 'mongoid', '3.1.6'

Gemfile.lock指出:

代码语言:javascript
复制
mongoid (3.1.6)
  activemodel (~> 3.2)
  moped (~> 1.4)
  origin (~> 1.0)
  tzinfo (~> 0.3.29)

下面是应该更新计数器的模型:

代码语言:javascript
复制
class Presentation
  include Mongoid::Document
  include Mongoid::Timestamps

  belongs_to :operation, :inverse_of => :presentations, :counter_cache => true

  after_save :update_counter

  def update_counter
    self.operation_id_change.each do |e|
      Operation.reset_counters(e, :presentations) unless e.nil?
    end
  end
end

以下是计数器字段的模型:

代码语言:javascript
复制
class Operation
  include Mongoid::Document
  include Mongoid::Timestamps

  field :presentations_count, type: Integer

  has_many :presentations, :inverse_of => :operation, dependent: :destroy
end
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-20 19:49:42

看起来你只是有一个命名空间问题。如果仔细观察错误:

代码语言:javascript
复制
undefined method ... for Mongoid::Persistence::Atomic::Operation:Module

您将看到,它在抱怨无法在reset_counters中找到Mongoid::Persistence::Atomic::Operation,而不是Operation。如果您查看3.1.6源代码,您将在Operation中找到lib/mongoid/persistence/atomic/operation.rb

如果为Operation指定了完全限定的名称

代码语言:javascript
复制
def update_counter
  self.operation_id_change.each do |e|
    ::Operation.reset_counters(e, :presentations) unless e.nil?
  # ^^
  end
end

然后,它将调用右边的reset_counters模块。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28624725

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档