我有以下范围:
scope :comments, :conditions => ['text_value IS NOT NULL']
但是我也希望条件说“OR text_value IS not EMPTY”(或者那种效果)。
我不想选择text_value
为空/空白的任何行。
答案 0 :(得分:56)
在Rails 4中你可以做到
where.not(text_value: '')
答案 1 :(得分:44)
正如Erwin所指出的,在这种情况下,简单的text_value <> ''
比较将起作用。
scope :comments, where("text_value <> ''")
(Rails 3更喜欢scope
的此查询语法 - 以及find
,all
等等 - 而不是选项哈希,例如:conditions => ...
。后者是deprecated in Rails 3.1。)
在Rails 4中,第二个参数应该是lambda而不是:
scope :comments, ->{ where("text_value <> ''") }
答案 2 :(得分:29)
rails 4
scope :comments, -> { where.not(:text_value => nil) }
答案 3 :(得分:8)
使用text_value <> ''
有效覆盖两个个案。
对TRUE
text_value
和NULL
empty
只会{{1}}。
答案 4 :(得分:3)
scope :comments, where("text_value <> ''")
答案 5 :(得分:1)
我个人这样做:
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) }
祝你好运!