您使用的是哪个版本的 Mongoid?因为当我尝试Model.none 时,它返回一个空集:
Model.none
Model.none.count # => 0
none 是在版本 4 中添加的。如果您无法更新到该版本,您可以尝试集成更改。 at line 309 in /lib/mongoid.criteria.rb 的这些方法需要定义:
def none
@none = true and self
end
def empty_and_chainable?
!!@none
end
Mongoid::Contextual#create_context也需要to be changed:
def create_context
return None.new(self) if empty_and_chainable?
embedded ? Memory.new(self) : Mongo.new(self)
end
那么你可以包含`/lib/mongoid/contextual/none.rb'。
编辑:this Gist backports .none to Mongoid 3:
module Mongoid
class Criteria
def none
@none = true and self
end
def empty_and_chainable?
!!@none
end
end
module Contextual
class None
include ::Enumerable
# Previously included Queryable, which has been extracted in v4
attr_reader :collection, :criteria, :klass
def blank?
!exists?
end
alias :empty? :blank?
attr_reader :criteria, :klass
def ==(other)
other.is_a?(None)
end
def each
if block_given?
[].each { |doc| yield(doc) }
self
else
to_enum
end
end
def exists?; false; end
def initialize(criteria)
@criteria, @klass = criteria, criteria.klass
end
def last; nil; end
def length
entries.length
end
alias :size :length
end
private
def create_context
return None.new(self) if empty_and_chainable?
embedded ? Memory.new(self) : Mongo.new(self)
end
end
module Finders
delegate :none, to: :with_default_scope
end
end