Mongoid 3.1.6 的未定义方法“reset_counters”
Undefined method `reset_counters' for Mongoid 3.1.6
我刚刚将我的 mongoid 更新到版本 3.1.6,这样我就可以使用 reset_counters 方法来跟踪我的模型关系。但正如我在 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
看来您只是遇到了命名空间问题。如果您仔细查看错误:
undefined method ... for Mongoid::Persistence::Atomic::Operation:Module
您会看到它抱怨无法在 Mongoid::Persistence::Atomic::Operation
中找到 reset_counters
,而不是 Operation
。如果您查看 3.1.6 源代码,您会在 lib/mongoid/persistence/atomic/operation.rb
.
中找到 Operation
如果您为 Operation
指定完全限定名称:
def update_counter
self.operation_id_change.each do |e|
::Operation.reset_counters(e, :presentations) unless e.nil?
# ^^
end
end
然后会调用右边的Operation
模块reset_counters
。
我刚刚将我的 mongoid 更新到版本 3.1.6,这样我就可以使用 reset_counters 方法来跟踪我的模型关系。但正如我在 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
看来您只是遇到了命名空间问题。如果您仔细查看错误:
undefined method ... for Mongoid::Persistence::Atomic::Operation:Module
您会看到它抱怨无法在 Mongoid::Persistence::Atomic::Operation
中找到 reset_counters
,而不是 Operation
。如果您查看 3.1.6 源代码,您会在 lib/mongoid/persistence/atomic/operation.rb
.
Operation
如果您为 Operation
指定完全限定名称:
def update_counter
self.operation_id_change.each do |e|
::Operation.reset_counters(e, :presentations) unless e.nil?
# ^^
end
end
然后会调用右边的Operation
模块reset_counters
。