ActiveAdmin Tables

ActiveAdmin has three main table options on the show page of a resource:

  1. attributes_table: table for the object at hand (i.e. for the Post#show page, a table for @post)
  2. attributes_table_for: table for a related resource (i.e. @post.user)
  3. table_for: table for a collection of related resources (i.e. @post.comments)

The documentation does not cover these tables in detail, so hopefully this post will save you some digging.

Suppose we have Post, Reaction, and User models.  A post has_many reactions and a post belongs_to a user.  On the Post#show page in ActiveAdmin, we want to create a table that shows the title, body, and user email attributes of the post. Since we are on the Post#show page, we can simply use and attributes_table and ActiveAdmin automatically knows that the object being referenced is the post.

show do
  attributes_table do
    row :id
    row :title
    row :body
  end
end

This is what the attributes_table looks like:
Screen Shot 2013-05-21 at 11.53.47 PM

Now we want to create a table for the user attribute that shows the id and email attributes. Remember that a user has_many posts and a post belongs_to a user.

panel "User" do
  attributes_table_for post.user do
    row :id
    row :email
  end
end

The attributes_table_for takes a single object as an argument. It must be wrapped in a panel to preserve the standard ActiveAdmin table formatting. Here is the user table:
Screen Shot 2013-05-22 at 12.00.14 AM

To create a table that shows all the reactions for a post, we use the table_for method, which takes a collection of objects as an argument. Here is how we can make a table that shows the id and body of each reaction as well as the user email for the user that made the reaction.

panel "Reactions" do
  table_for post.reactions do
    column :id
    column :body
    column "Email" do |reaction|
      reaction.user.email
    end
  end
end

The table_for method also needs to be wrapped in a panel to preserve the standard ActiveAdmin formatting. Here is what the reaction table looks like:
Screen Shot 2013-05-22 at 12.06.16 AM

ActiveAdmin has three helper methods: one for the implicit object, one for any single object, and another for a collection of objects. The documentation does not make these methods obvious, but they are very useful. If you need more practice, check out this CodeQuiz that shows all three ActiveAdmin tables in action.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s