Custom controller actions in ActiveAdmin (Ruby on Rails)

ActiveAdmin is a popular Ruby on Rails plugin for creating admin area. It helps developers solve many common problems to view/edit data as administrator. There are several other similar plugins, but I prefer ActiveAdmin because it allows developers to customize almost everything.

This post shows how to to add a custom action to an ActiveAdmin controller.

The scenario:

We want to add a custom action to our ‘products’ resource as follows:

– Custom member action – page ‘import’ which will have a form to do something with a product;

– Custom ‘collection’ action that will do some stuff;

– Custom controller action to process the form;

– Custom controller action to process the ‘collection’ command;

– Links to access new pages

 

The Solution

Register our Product model with ActiveAdmin:



 

After that your can edit products using the power of ActiveAdmin.

We will use member actions to customize ActiveAdmin controller. Member action is a controller action which operates on a single resource.

Create actions to show a view with a form and process the post from form:



 

This generates routes:

– showimport_admin_product_path(product_object) equals to ‘/admin/products/:id/showimport’ pointing to the Admin::ProductsController#showimport controller action.

– import_admin_product_path(product_object) equals to ‘/admin/products/:id/import’ pointing to the controller action ‘import”.

 

Create a view which will be rendered from ‘showimport’ action (file ‘app/views/admin/products/showimport.html.haml’ ):


 

Add your code to the custom controller action ‘import’ to process the form:



 

 

Custom collection action

A collection action is a controller action which operates on the collection of resources.

Declare collection action:



 

This will generate the route ‘dosmth_admin_products_path’.

Place your code in the controller action:



 

All code is available on Github Gists.

 

 

 

 

One thought on “Custom controller actions in ActiveAdmin (Ruby on Rails)”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>