Ruby-on-rails 选择 mongoid 中不为 null 或为空的地方
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10337847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select where not null or empty in mongoid
提问by methodofaction
I modified a model so it includes a new field, such as...
我修改了一个模型,使其包含一个新字段,例如...
field :url, :type => String
field :url, :type => String
I use activeadmin, so when I create a new entry @model.urlis empty, and in entries created before changing the schema it's nil. How do I select both? I have tried:
我使用activeadmin,所以当我创建一个新条目时@model.url是空的,并且在更改架构之前创建的条目中它为零。我如何选择两者?我试过了:
# 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
Or, if there's a best practice for this kind of scenario please let me know.
或者,如果有这种场景的最佳实践,请告诉我。
回答by Kyle
Try
尝试
Model.where(:url.ne => "", :url.exists => true).count
回答by a14m
Try
尝试
Model.where(:url.nin => ["", nil]).count
It works even when url = nil
它即使在 url = nil
回答by p.matsinopoulos
Try:
尝试:
Model.nin(url: ['', nil])

