Rails的范围是不是空的,不是空的/空的?
我有以下范围:
scope :comments, :conditions => ['text_value IS NOT NULL']
但是我也想要条件说“OR text_value不是空的”(或者是这个效果)。
我不想selecttext_value为空/空白的任何行。
正如Erwin指出的那样,在这种情况下,一个简单的text_value <> ''比较就可以工作。
scope :comments, where("text_value <> ''")
(Rails 3更喜欢这个查询语法的scope以及find , all等等,而不是一个选项哈希例如:conditions => ...后者在Rails 3.1中不推荐使用 。
在Rails 4中,第二个参数应该是lambda:
scope :comments, ->{ where("text_value <> ''") }
在Rails 4中你可以做
where.not(text_value: '')
导轨4
scope :comments, -> { where.not(:text_value => nil) }
使用text_value <> ''来有效地覆盖这两种情况。
对于既不为NULL也不为empty的text_value只会为TRUE 。
scope :comments, where("text_value <> ''")
我个人是这样做的:
1)添加到初始化程序
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)添加到您的模型
scope :comments, -> { where(arel_table[:text_value].is_not_empty) }
祝你好运!