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

前端 未结 6 579
没有蜡笔的小新
没有蜡笔的小新 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: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!

提交回复
热议问题