Select where not null or empty in mongoid

methodofaction picture methodofaction · Apr 26, 2012 · Viewed 38.3k times · Source

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.

Answer

Kyle picture Kyle · Apr 26, 2012

Try

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

see Mongoid Symbol Operators