簡體   English   中英

過濾值或在activeadmin中為IS NULL

[英]Filter for values OR IS NULL in activeadmin

鑒於我有兩個模型:

class Post < ActiveRecord::Base
  belongs_to :district
end

class District < ActiveRecord::Base
  has_many :posts
end

我需要在帖子頁面上的check_boxes中創建一個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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM