【发布时间】:2012-01-27 01:53:18
【问题描述】:
我的范围如下:
scope :comments, :conditions => ['text_value IS NOT NULL']
但我也希望条件说“OR text_value IS NOT EMPTY”(或类似的意思)。
我不想选择text_value 为空/空白的任何行。
【问题讨论】:
标签: sql ruby-on-rails postgresql scope
我的范围如下:
scope :comments, :conditions => ['text_value IS NOT NULL']
但我也希望条件说“OR text_value IS NOT EMPTY”(或类似的意思)。
我不想选择text_value 为空/空白的任何行。
【问题讨论】:
标签: sql ruby-on-rails postgresql scope
我个人是这样的:
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) }
祝你好运!
【讨论】:
正如 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 <> ''") }
【讨论】:
COALESCE() 在这种情况下显得很笨拙,因为NULL <> '' 会产生NULL。只有TRUE 条件限定一行。
where.not(text_value: [nil, ""])
在 Rails 4 中你可以这样做
where.not(text_value: '')
【讨论】:
text_value <> '')。诚然,这有点 SQL 的魔力……
导轨 4
scope :comments, -> { where.not(:text_value => nil) }
【讨论】:
scope :comments, where("text_value <> ''")
【讨论】:
OR 是错误的运算符。这将接受一个空的text_value。
text_value IS NOT NULL。请参阅我的回答和其他评论。运算符 <> 和 != 对于字符类型(以及大多数其他类型)是相同的。
使用text_value <> '' 有效地涵盖两种情况。
对于既不是NULL 也不是empty 的text_value 只会是TRUE。
【讨论】: