Peter
Peter

Reputation: 555

ActiveAdmin: how to add second custom index table page

Users of some admin need to have two table views of, say, a model Bar: default one they already have and an additional new one with different set of columns.

The setting is such:

ActiveAdmin.register Bar do
  # …
  index do
    column :name
    column :phone
    column :address
  end
  # …

It's expected to be as easy as adding another index block as in:

ActiveAdmin.register Bar do
  # …
  index do
    column :name
    column :price
    column :bartender
  end

  index name: 'location' do
    column :name
    column :phone
    column :city
    column :country
  end

and then just get the additional tab somewhere.

As you may guess it is not that simple. ActiveAdmin nows nothing about the imaginary index name: attribute and just selects the first index block silently ignoring the second index block.

ActiveAdmin documentation shows a way to add second/third/etc index page with ease but of a different kind:

index as: :grid do |bar|
  link_to(image_tag(bar.photo_path), admin_bar_path(bar))
end

Nice, but how to add a duplicate of the index table view with different columns?

Upvotes: 1

Views: 3013

Answers (1)

Peter
Peter

Reputation: 555

There is a trick.

As show before ActiveAdmin's index method allows the as: argument with the type of the index coded as symbol (ATM, one of these: :block, :blog, :grid and :table). Alongside with symbols (which are just shortcuts for some internal AA classes) it's possible to pass any Ruby class:

index as: CustomTableIndex do
  # …
end

Here is the code for the solution. Four things to do for our new table index page:

  1. create a subclass of ActiveAdmin::Views::IndexAsTable
  2. define a class method index_name in the subclass with a name of the new index page
  3. pass the new class to the index method
  4. add a i18n translation for the new tab button (if necessary)

in app/admin/bars.rb:

ActiveAdmin.register Bar do

  # …

  # 1.
  class MyLocationIndex < ActiveAdmin::Views::IndexAsTable
    # 2.
    def self.index_name
      "bars_location"
    end
  end

  # 3.
  index as: MyLocationIndex do
    column :name
    column :phone
    column :city
    column :country
  end

  # …

end

in config/locales/admin.yml:

en:
  # …
  active_admin:
    index_list:
      bars_location: "Locations"

Upvotes: 5

Related Questions