我有以下范围:
scope :comments, :conditions => ['text_value IS NOT NULL']
但我也希望条件说"OR text_value IS NOT EMPTY"(或类似的东西)。
我不想选择text_value
为空/空白的任何行
在Rails 4中你可以做
where.not(text_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
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) }
祝你好运!