SQL IS NOT NULL 的 Rails 范围并且不为空/空白?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8620547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 13:44:30  来源:igfitidea点击:

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

sqlruby-on-railspostgresqlscope

提问by Shpigford

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).

但我也希望条件说“OR text_value IS NOT EMPTY”(或类似的东西)。

I don't want to select any rows where text_valueis empty/blank.

我不想选择任何text_value空/空白的行。

回答by Patrick Oscity

In Rails 4 you can do

在 Rails 4 中你可以做

where.not(text_value: '')

回答by Jordan Running

As Erwin points out, a simple text_value <> ''comparison will work in this case.

正如 Erwin 所指出的,text_value <> ''在这种情况下可以进行简单的比较。

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.)

(导轨3喜欢此查询语法scope-as以及findall等等-而不是一个选项散列例如:conditions => ...,后者是在滑轨3.1弃用)。

In Rails 4, the second argument should be a lambda instead:

在 Rails 4 中,第二个参数应该是一个 lambda:

scope :comments, ->{ where("text_value <> ''") }

回答by miclle

rails 4

导轨 4

scope :comments, -> { where.not(:text_value => nil) }

回答by Erwin Brandstetter

Use text_value <> ''to efficiently cover bothcases.

使用text_value <> ''以有效地覆盖这两种情况。

Will only be TRUEfor a text_valuethat is neither NULLnor empty.

只会TRUE用于text_value既不是也不NULLempty

回答by Marek P?íhoda

scope :comments, where("text_value <> ''")

回答by yivo

Personally I am doing like this:

我个人是这样做的:

1) Add to initializers

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) Add to your model

2)添加到您的模型

scope :comments, -> { where(arel_table[:text_value].is_not_empty) }

Good luck!

祝你好运!