【问题标题】:Select where not null or empty in mongoid选择 mongoid 中不为空或为空的位置
【发布时间】:2012-05-07 10:43:48
【问题描述】:

我修改了一个模型,使其包含一个新字段,例如...

field :url, :type => String

我使用 activeadmin,所以当我创建一个新条目时,@model.url 是空的,而在更改架构之前创建的条目中它是 nil。如何选择两者?我试过了:

# Returns nils and strings
Model.where(:url.ne => "").count 

# Returns strings and ""
Model.where(:url.ne => nil).count

# Returns strings, nils and ""
Model.where(:url.ne => ["", nil]).count 

或者,如果有适合这种情况的最佳做法,请告诉我。

【问题讨论】:

    标签: ruby-on-rails mongoid


    【解决方案1】:

    试试:

    Model.nin(url: ['', nil])
    

    【讨论】:

      【解决方案2】:

      试试

      Model.where(:url.nin => ["", nil]).count
      

      即使url = nil 也能正常工作

      【讨论】:

      • 我同意,这是真正的答案,应该是这个问题的公认答案。
      • 如果您只想检查字段不为零的条目:Model.where(:field.ne=>nil)
      【解决方案3】:

      试试

      Model.where(:url.ne => "", :url.exists => true).count
      

      Mongoid Symbol Operators

      【讨论】:

        猜你喜欢
        • 2018-07-06
        • 2014-04-13
        • 2011-05-27
        • 1970-01-01
        • 1970-01-01
        • 2020-07-07
        • 2011-06-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多