Skip to content

Instantly share code, notes, and snippets.

@glaszig
Created March 10, 2016 11:57
Show Gist options
  • Save glaszig/f51ffee2b71ab66edcc2 to your computer and use it in GitHub Desktop.
Save glaszig/f51ffee2b71ab66edcc2 to your computer and use it in GitHub Desktop.
Grouped table index for 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
@bcipriano
Copy link

bcipriano commented Sep 21, 2019

This was a huge help, thank you!!

It's a bit old but is still ranked high in Google search results, so I wanted to add a few things --

  • I created my view file as app/admin/ui/index_as_grouped_table.rb. For that reason (I'm assuming) I didn't need the application.rb changes listed here -- ActiveAdmin already searches app/admin apparently.

  • My code has some minor changes -- namely I'm inheriting instead from IndexAsReorderableTable (from the activeadmin_reorderable Gem in order to get drag-and-drop reordering functionality.

class IndexAsGroupedReorderableTable < ActiveAdmin::Views::IndexAsReorderableTable

  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

Just wanted to add that in case it's helpful to someone in the future!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment