I am trying to find records where a specified property is not empty or blank. Since it is a string it is not nil in the database.
Post.where(:sourceurl != '')
The above seems like it should work but I still get records returned where the source_url property is empty. What is the proper way to do this?
ActiveRecord (in Rails 3 and 4, i think) allows for checking multiple conditions by passing an Array as an argument. So if you wanted to check for both nil
and ''
, you can use:
where(sourceurl: [nil, ''])
This will generate an SQL conditional like:
(sourceurl IS NULL OR sourceurl = '')
In Rails 4, you can check for the negative condition with .not, so for the original question, you could do:
Post.where.not(sourceurl: [nil, ''])
.not has a bit of magic that makes it advantageous to a pure SQL query because it works across databases, does NOT NULL queries automatically, and a few more things as explained here: where.not explained
try this
Post.where("sourceurl <> ''")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With