【问题标题】:Mongoid criteria that returns nothing什么都不返回的 Mongoid 标准
【发布时间】:2014-05-13 14:13:39
【问题描述】:

我需要创建一个不会返回任何内容的 mongoid 标准。我找不到任何“无”的方法,所以我正在做 Model.where(id: nil) 或 Model.any_in(id: nil) 。 不过这样不好,还会查询数据库。

我想将我自己的选择器添加到 mongoid 中,这将返回一个空结果,甚至无需查询数据库(例如 Model.none()),但不知道在哪里/如何做。有人可以帮忙吗?

注意:我需要这个,因为调用者可能会在不知道它已经为空的情况下链接条件。

【问题讨论】:

    标签: ruby-on-rails mongoid


    【解决方案1】:

    您使用的是哪个版本的 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
    

    【讨论】:

    • 对,存在于版本 4 中,但不存在于我使用的 3.1.4 中。然后,我将尝试将 None 类复制到我的项目中。或者这不是一个好主意?
    • 我用我认为应该可以整合None的内容更新了我的答案。这可能是不受欢迎的,但这些变化似乎并没有那么深远,所以看起来还可以。
    • 所以我试图像这样gist.github.com/stanley90/5a5f35be733642e2afc9(在配置/初始化程序中)进行猴子修补,但不起作用。我做错了吗?
    • 啊,这不是一个错误。嗯,我的主旨也不行。让我看看……
    猜你喜欢
    • 2015-04-08
    • 1970-01-01
    • 2016-11-05
    • 2012-06-18
    • 2018-09-10
    • 2017-02-14
    • 2013-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多