使用 2 级数组在 ActiveAdmin 中自定义过滤器
Custom filter in ActiveAdmin using 2 level array
目前我有一个带有过滤器的 Case 模型:
filter :specialty, as: :select, collection: Specialty.order(:category, :name)
过滤器下拉列表显示如下:
category1 - name1
category1 - General
category1 - name2
category2 - name1
category2 - name2
category2 - name3
:name
下有一个字符串 General
,我总是希望它位于按字母顺序排序的列表的顶部。因此过滤器将始终按字母顺序显示 :category
,然后按字母顺序显示 :name
。
我希望此下拉菜单显示以下内容:
category1 - General
category1 - name1
category1 - name2
category2 - name1
category2 - name2
category2 - name3
我决定在案例模型中编写一个方法,以便我可以在 AA 过滤器中调用它,如下所示:
filter :specialty, as: :select, collection: Specialty.my_method
my_method
目前看起来像这样:
def self.my_method
groups = []
category_list = Specialty.distinct(:category).pluck(:category, :name)
category_list.sort_by! do |category, name|
name == 'General' ? "#{category}, #{''}" : "#{category}, #{name}"
end
category_list.each do |category|
groups << [category, Specialty.where(category: category).order('name')]
end
return groups
end
问题是这会将下拉列表显示为数组而不是字符串,它看起来像这样:
["category1", "General"]
["category1", "name1"]
["category1", "name2"]
["category2", "name1"]
["category2", "name2"]
["category2", "name3"]
如何修改我的代码以使其正确显示?
搜查与此有关系吗?
return groups.map{|group| group.join(" ")}
原来是我对查询算法想多了。这是使 return 成为正确数组的代码。
def self.my_method
all.sort_by do |specialty|
specialty.name == 'General' ? [specialty.category, ''] :
[specialty.category, specialty.name]
end
end
下拉列表现在显示:
category1 - General
category1 - name1
category1 - name2
category2 - name1
category2 - name2
category2 - name3
目前我有一个带有过滤器的 Case 模型:
filter :specialty, as: :select, collection: Specialty.order(:category, :name)
过滤器下拉列表显示如下:
category1 - name1
category1 - General
category1 - name2
category2 - name1
category2 - name2
category2 - name3
:name
下有一个字符串 General
,我总是希望它位于按字母顺序排序的列表的顶部。因此过滤器将始终按字母顺序显示 :category
,然后按字母顺序显示 :name
。
我希望此下拉菜单显示以下内容:
category1 - General
category1 - name1
category1 - name2
category2 - name1
category2 - name2
category2 - name3
我决定在案例模型中编写一个方法,以便我可以在 AA 过滤器中调用它,如下所示:
filter :specialty, as: :select, collection: Specialty.my_method
my_method
目前看起来像这样:
def self.my_method
groups = []
category_list = Specialty.distinct(:category).pluck(:category, :name)
category_list.sort_by! do |category, name|
name == 'General' ? "#{category}, #{''}" : "#{category}, #{name}"
end
category_list.each do |category|
groups << [category, Specialty.where(category: category).order('name')]
end
return groups
end
问题是这会将下拉列表显示为数组而不是字符串,它看起来像这样:
["category1", "General"]
["category1", "name1"]
["category1", "name2"]
["category2", "name1"]
["category2", "name2"]
["category2", "name3"]
如何修改我的代码以使其正确显示? 搜查与此有关系吗?
return groups.map{|group| group.join(" ")}
原来是我对查询算法想多了。这是使 return 成为正确数组的代码。
def self.my_method
all.sort_by do |specialty|
specialty.name == 'General' ? [specialty.category, ''] :
[specialty.category, specialty.name]
end
end
下拉列表现在显示:
category1 - General
category1 - name1
category1 - name2
category2 - name1
category2 - name2
category2 - name3