Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails scope for IS NOT NULL and is not empty/blank?

I have the following scope:

scope :comments, :conditions => ['text_value IS NOT NULL'] 

But I also want the conditions to say "OR text_value IS NOT EMPTY" (or something to that effect).

I don't want to select any rows where text_value is empty/blank.

like image 944
Shpigford Avatar asked Dec 23 '11 20:12

Shpigford


2 Answers

In Rails 4 you can do

where.not(text_value: '') 
like image 77
Patrick Oscity Avatar answered Sep 23 '22 13:09

Patrick Oscity


As Erwin points out, a simple text_value <> '' comparison will work in this case.

scope :comments, where("text_value <> ''") 

(Rails 3 prefers this query syntax for scope—as well as find, all, etc.—rather than an options hash e.g. :conditions => .... The latter is deprecated in Rails 3.1.)

In Rails 4, the second argument should be a lambda instead:

scope :comments, ->{ where("text_value <> ''") } 
like image 44
Jordan Running Avatar answered Sep 23 '22 13:09

Jordan Running