gpt4 book ai didi

ruby-on-rails - activeadmin 资源索引页面上的组记录

转载 作者:行者123 更新时间:2023-12-03 21:38:13 24 4
gpt4 key购买 nike

我有 2 个资源 - 书架和书,每个书架都有很多书。

有没有办法按书架对书籍(在书籍索引页面上)进行分组?具体来说,我希望按书架对书籍进行排序,并且每当书架发生变化时,我想在书籍列表中指出这一点(在一个书架上的书籍和另一个书架上的书籍之间插入一个带有新书架名称的 h3 标题)

我正在使用 rails 3.2 和 activeadmin 0.6.0。

最佳答案

在 Rails 4.2.5.2 上使用 ActiveAdmin 1.0.0.pre2,结果非常简单。该解决方案本质上只有 20 行自定义 ActiveAdmin View 类。

note the file names on the first line as a hint where to put the code or make additions/changes to existing files.



# 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 中到底发生了什么:

类(class) IndexAsGroupedTable扩展 ActiveAdmin 的 IndexAsTable类并覆盖 build添加分组功能的方法。
在您的 admin/books.rb文件,在索引宏中,您定义了一个附加选项 :group_by_attribute它命名 Book上的属性名称分组的类。
如果未提供该属性,则回退到 IndexAsTable的行为。
如果提供了该属性,它将 group_by该属性的集合, sort散列并使用每个 group_name 运行一个 block 和 group_collection从那个哈希,打印一个 <h3>group_name然后调用 IndexAsTablebuild方法 ( super) 来显示标准表。

如您所见,仅对组进行了排序,并将 h3 添加到页面中。其他一切都像标准索引表一样工作。

note: this does not involve additional sql for the grouping. this uses ruby's group_by method of the Enumerable class. thus, it may be slow if you have many rows in the collection.



对于最新版本和/或 fork ,请访问我的 my gist on github .

该方法的学分转到ariejan de vroom .

关于ruby-on-rails - activeadmin 资源索引页面上的组记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17349856/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com