LoginSignup
2
1

More than 5 years have passed since last update.

ransack で xxx_or_null を使って検索できるようにする

Posted at

参考
+ https://github.com/activerecord-hackery/ransack/issues/123#issuecomment-247083120

config/initializers/ransack.rb
module Arel
  module Predications
    def eq_or_null(other)
      left  = eq(other)
      right = eq(nil)
      left.or(right)
    end

    def not_eq_or_null(other)
      left  = not_eq(other)
      right = eq(nil)
      left.or(right)
    end

    def gteq_or_null(other)
      left  = gteq(other)
      right = eq(nil)
      left.or(right)
    end

    def lt_or_null(other)
      left  = lt(other)
      right = eq(nil)
      left.or(right)
    end

    def in_or_null(other)
      left  = self.in(other)
      right = eq(nil)
      left.or(right)
    end
  end
end

Ransack.configure do |config|
  config.add_predicate 'eq_or_null', arel_predicate: 'eq_or_null'
  config.add_predicate 'not_eq_or_null', arel_predicate: 'not_eq_or_null'
  config.add_predicate 'gteq_or_null', arel_predicate: 'gteq_or_null'
  config.add_predicate 'lt_or_null', arel_predicate: 'lt_or_null'
  config.add_predicate 'in_or_null', arel_predicate: 'in_or_null', wants_array: true
end
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1