在 Rails 4.2.5.2 上使用 ActiveAdmin 1.0.0.pre2,结果非常简单。该解决方案基本上只有 20 行自定义 ActiveAdmin 视图类。
记下第一行的文件名,作为放置代码或对现有文件进行添加/更改的提示。
# config/application.rb
module MyApp
class Application < Rails::Application
config.autoload_paths << config.root.join('lib')
end
end
# models/book.rb
class Book < ActiveRecord::Base
belongs_to :shelf
def shelf_name
shelf.name
end
end
# admin/books.rb
ActiveAdmin.register Book do
index as: :grouped_table, group_by_attribute: :shelf_name do
# columns
end
end
# lib/active_admin/views/index_as_grouped_table.rb
require 'active_admin/views/index_as_table'
module ActiveAdmin
module Views
class IndexAsGroupedTable < IndexAsTable
def build(page_presenter, collection)
if group_by_attribute = page_presenter[:group_by_attribute]
collection.group_by(&group_by_attribute).sort.each do |group_name, group_collection|
h3 group_name
super page_presenter, group_collection
end
else
super
end
end
end
end
end
让我解释一下 index_as_grouped_table.rb 发生了什么他妈的:
IndexAsGroupedTable 类扩展了 ActiveAdmin 的 IndexAsTable 类并覆盖了 build 方法以添加分组功能。
在您的admin/books.rb 文件中,在索引宏中,您定义了一个附加选项:group_by_attribute,该选项命名Book 类上的属性名称,以用于分组。
如果没有提供该属性,它会退回到IndexAsTable 的行为。
如果提供了该属性,它将 group_by 该属性的集合,sort 哈希并使用该哈希中的每个 group_name 和 group_collection 运行一个块,打印带有 group_name 的 <h3>然后只需调用IndexAsTable 的build 方法(super)即可显示标准表。
如您所见,仅对组进行了排序,并将 h3 添加到页面中。其他一切都像标准索引表一样工作。
注意:这不涉及用于分组的额外 sql。这使用了 Enumerable 类的 ruby 的 group_by 方法。因此,如果集合中有很多行,它可能会很慢。
如需最新版本和/或分叉,请访问我的my gist on github。
该方法的功劳转到ariejan de vroom。