我刚刚将mongoid更新为3.1.6版本,以便可以使用计数器方法跟踪我的模型关系。但是,正如我在gem更新之前所做的那样,我仍然会得到以下错误:
undefined method `reset_counters' for Mongoid::Persistence::Atomic::Operation:Module在我的Gemfile中,我有这样的版本:
gem 'mongoid', '3.1.6'Gemfile.lock指出:
mongoid (3.1.6)
activemodel (~> 3.2)
moped (~> 1.4)
origin (~> 1.0)
tzinfo (~> 0.3.29)下面是应该更新计数器的模型:
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以下是计数器字段的模型:
class Operation
include Mongoid::Document
include Mongoid::Timestamps
field :presentations_count, type: Integer
has_many :presentations, :inverse_of => :operation, dependent: :destroy
end发布于 2015-02-20 19:49:42
看起来你只是有一个命名空间问题。如果仔细观察错误:
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指定了完全限定的名称
def update_counter
self.operation_id_change.each do |e|
::Operation.reset_counters(e, :presentations) unless e.nil?
# ^^
end
end然后,它将调用右边的reset_counters模块。
https://stackoverflow.com/questions/28624725
复制相似问题