I have the following scope:
scope :comments, :conditions => [\'text_value IS NOT NULL\']
But I also want the conditions to say \"OR text_val
Use text_value <> ''
to efficiently cover both cases.
Will only be TRUE
for a text_value
that is neither NULL
nor empty
.
scope :comments, where("text_value <> ''")
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 <> ''") }
rails 4
scope :comments, -> { where.not(:text_value => nil) }
Personally I am doing like this:
1) Add to initializers
class Arel::Attributes::Attribute
# Encode column name like: `posts`.`author_id`
def to_sql
"`#{relation.table_name}`.`#{name}`"
end
def is_not_empty
"#{to_sql} <> ''"
end
end
2) Add to your model
scope :comments, -> { where(arel_table[:text_value].is_not_empty) }
Good luck!
In Rails 4 you can do
where.not(text_value: '')