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

前端 未结 6 580
没有蜡笔的小新
没有蜡笔的小新 2021-01-30 05:20

I have the following scope:

scope :comments, :conditions => [\'text_value IS NOT NULL\']

But I also want the conditions to say \"OR text_val

相关标签:
6条回答
  • 2021-01-30 05:42

    Use text_value <> '' to efficiently cover both cases.

    Will only be TRUE for a text_value that is neither NULL nor empty.

    0 讨论(0)
  • 2021-01-30 05:44
    scope :comments, where("text_value <> ''")
    
    0 讨论(0)
  • 2021-01-30 05:49

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

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

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

    scope :comments, ->{ where("text_value <> ''") }
    
    0 讨论(0)
  • 2021-01-30 05:49

    rails 4

    scope :comments, -> { where.not(:text_value => nil) }
    
    0 讨论(0)
  • 2021-01-30 05:52

    Personally I am doing like this:

    1) Add to initializers

    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

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

    Good luck!

    0 讨论(0)
  • 2021-01-30 06:06

    In Rails 4 you can do

    where.not(text_value: '')
    
    0 讨论(0)
提交回复
热议问题