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

2019-03-08 05:21发布

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.

6条回答
Evening l夕情丶
2楼-- · 2019-03-08 05:46

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 <> ''") }
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-03-08 05:46
scope :comments, where("text_value <> ''")
查看更多
SAY GOODBYE
4楼-- · 2019-03-08 05:50

In Rails 4 you can do

where.not(text_value: '')
查看更多
姐就是有狂的资本
5楼-- · 2019-03-08 05:55

rails 4

scope :comments, -> { where.not(:text_value => nil) }
查看更多
走好不送
6楼-- · 2019-03-08 05:55

Use text_value <> '' to efficiently cover both cases.

Will only be TRUE for a text_value that is neither NULL nor empty.

查看更多
疯言疯语
7楼-- · 2019-03-08 06:06

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!

查看更多
登录 后发表回答