Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails ActiveRecord where property is not blank

Tags:

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?

like image 904
Jason Yost Avatar asked Jul 22 '12 10:07

Jason Yost


2 Answers

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

like image 57
kindofgreat Avatar answered Oct 12 '22 00:10

kindofgreat


try this

Post.where("sourceurl <> ''") 
like image 25
abhas Avatar answered Oct 12 '22 00:10

abhas