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

标签 ruby-on-rails ruby-on-rails-3.2 grouping activeadmin

我有 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/

相关文章:

ruby-on-rails - 错误-迁移正在进行中。要解决此问题,请运行:bin/rake db:migrate RAILS_ENV = development

ruby-on-rails - Rails 5 中的弃用警告

javascript - 您最喜欢兼容 Prototype 框架的 javascript 日期选择器是什么?

ruby-on-rails-3.2 - 如何在 STI 的开发环境中重新加载 app/models/subdirectory 中的文件

ruby-on-rails - 网络模拟 : Rspec - Test Facebook Validation by using JSON response

升级到 jQuery UI 1.10.3 后,jQuery 自动完成下拉列表不显示

java - 如何按日期对对象列表进行分组?

javascript - 将客户端 JavaScript 中的数组或哈希传递到服务器端 ruby​​ 有哪些好方法?

Java Streams 列表将出现的索引映射为键

sqlite - 按数字或首字母分组