Select where not null or empty in mongoid

Ruby on-RailsMongoid

Ruby on-Rails Problem Overview


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.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Try

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

see Mongoid Symbol Operators

Solution 2 - Ruby on-Rails

Try

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

It works even when url = nil

Solution 3 - Ruby on-Rails

Try:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmethodofactionView Question on Stackoverflow
Solution 1 - Ruby on-RailsKyleView Answer on Stackoverflow
Solution 2 - Ruby on-Railsa14mView Answer on Stackoverflow
Solution 3 - Ruby on-Railsp.matsinopoulosView Answer on Stackoverflow