我有一个带有名为“map_id”的整数列的表,我想添加一个activeadmin过滤器来过滤该列是否为空或IS NOT NULL。
如何实施?
我尝试了以下过滤器
filter :map_id, :label => 'Assigned', :as => :select, :collection => {:true => nil, :false => ''}
但是,我收到以下错误消息:
#
的未定义方法`map_eq'答案 0 :(得分:28)
如果有人在这个线程上发生了迟来的事情,现在有一种简单的方法可以在活动管理中过滤null或非null:
filter :attribute_present, :as => :boolean
filter :attribute_blank, :as => :boolean
不再需要在范围中添加自定义方法来实现此目的。
答案 1 :(得分:12)
没有找到一个好的解决方案,但这是一个如何。 Active_admin的过滤器由meta_search完成,您可以覆盖模型中meta_search自动生成的函数以获得您想要的行为,最好的方法是使用范围,因为您需要返回一个关系以便与其他查询链接/ scopes,如here
所述在您的模型中:
for:as =>:选择过滤器,acitve_admin使用_eq wheres,这里是source code
scope :map_eq,
lambda{ |id|
if(id !='none')
where( :map_id=> id)
else
where( :map_id=> nil)
end
}
#re-define the search method:
search_method :map_eq, :type => :integer
你的ative_admin寄存器块中的:
filter :map_id, :label => 'Assigned', :as => :select, :collection => [['none', 'none'], ['one', 1],['tow', 2]]
# not using :none=>nil because active_admin will igore your nil value so your self-defined scope will never get chained.
希望得到这个帮助。
答案 2 :(得分:5)
似乎search_method在最近的rails版本中不起作用,这是另一个解决方案:
为您的模型添加范围:
scope :field_blank, -> { where "field is null" }
scope :field_not_blank, -> { where "field is not null" }
添加到/ app / admin / [您的模型]
scope :field_blank
scope :field_not_blank
您将看到这些范围的按钮出现(在顶部,模型名称下,而不是在过滤器部分)
答案 3 :(得分:1)
新版ActiveAdmin使用Ransacker。我设法以这种方式工作:
filter :non_nil_map_id, :label => 'Assigned', :as => :select, :collection => [['none', 'none'], ['one', 1],['tow', 2]]
为了保持一致性,我从@Gret中获取了相同的代码,只需更改过滤器名称
即可ransacker :not_nil_map_id, :formatter => proc {|id| map_id != 'none' ? id : 'none' } do |parent|
parent.table[:id]
end
如果id为'none',则应触发对 nil 的搜索,并且活动记录将返回所有 nil id 条目。
This thread帮助了很多。
答案 4 :(得分:-1)
具有无法检查的范围:
关于ActiveAdmin资源定义:
filter :map_id, :label => 'Assigned', as: :select, :collection => [['Is Null', 'none'], ['Not null', 'present']]
在您的模型上:
scope :by_map_id, ->(id) { (id == 'none' ? where(map_id: nil) : where('map_id IS NOT NULL')) }
def self.ransackable_scopes(_auth_object = nil)
%i[by_map_id]
end