过滤值或在activeadmin中为IS NULL

时间:2013-10-22 09:43:38

标签: ruby-on-rails activeadmin ransack

鉴于我有两个模型:

class Post < ActiveRecord::Base
  belongs_to :district
end

class District < ActiveRecord::Base
  has_many :posts
end

我需要在帖子页面上的ActiveAdmin中创建一个check_boxes过滤器,以便用户能够获取属于某些确切区域或根本不属于任何区域的帖子。

在ActiveAdmin将MetaSearch更改为Ransack之前,可以使用自定义范围完成。现在我什么都不知道。当我执行以下操作时:

filter :district_id_null, as: :boolean
filter :district, as: :check_boxes

它使条件WHERE district_id IN (1,2,3) AND district_id IS NULL(我需要OR而不是AND)。当我做的时候

filter :district, as: :check_boxes, collection: proc { District.unscoped.map { |x| [x.title, x.id] }.unshift ['Empty', 'null'] }

它使条件WHERE district_id IN (0,1,2,3)(但在大多数SQL数据库中,NULL不是0)。

1 个答案:

答案 0 :(得分:0)

我觉得这样的事情可能有用

class Post
    def self.ransack_with_or(search_params)
        params = search_params.deep_clone
        #check if we need OR
        if search_params.has_key?('district_id_in') && search_params.has_key?('district_id_null')
         params.delete('district_id_null')
         district_id_in = params.delete('district_id_in')
         #old behaviour without district_id_null and district_id_null attributes
         q = ransack_without_or(params)
         #here we're adding OR group 
         q.build_grouping({m: 'or', district_id_null: true, district_id_in: district_id_in}) 
        else
         #old behaviour we don't need OR
         q = ransack_without_or(params)
        end
        q
       end

       #wrapping ransack method 
       class << self
         alias_method_chain :ransack, :or
       end
    end