鉴于我有两个模型:
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)。 最佳答案
我认为这样的事情可能会起作用
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
关于ruby-on-rails - 在activeadmin中过滤值或IS NULL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19514312/