85
votes

I modified a model so it includes a new field, such as...

field :url, :type => String

I use activeadmin, so when I create a new entry @model.url is empty, and in entries created before changing the schema it's nil. How do I select both? I have tried:

# 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.

3

3 Answers

96
votes

Try

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

see Mongoid Symbol Operators

88
votes

Try

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

It works even when url = nil

7
votes

Try:

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