I've inherited the maintenance of some code that makes use of Active Admin. One of my first tasks is to add sorting to a table that was on a custom page. I couldn't find an idiomatic or documented way of handling this, but I think I've cobbled through a solution using a little spelunking. I'm very new to Active Admin, so in full honesty this is likely not the best solution.
The first step is to add the appropriate options to the table for
:
table_for users, {:sortable => true, :class => 'index_table'} do
...
end
The options {:sortable => true, :class => 'index_table'}
tell active admin that the table is sortable and put the class on the table so that it looks like the sortable index tables.
Next, we need to update the column definitions.
column('Email', :sortable => :user_email) {|user| user.email}
The sortable
option specifies the ‘field' that will be sorted. I chose user_email
in order to be able to differentiate between the different sortable tables on the page.
Finally we need to make use of the values that Active Admin will pass back to the controller when a user selects a sort on a table column.
order = case(params[:order])
when 'user_email_desc'
'email DESC'
when 'user_email_asc'
'email ASC'
else
nil
end
if(order.nil?)
users = User.all
else
users = User.order(order)
end
I used a case
statement to parse the value coming back from the page and call the appropriate order on the ActiveRecord model.
The final snippet looks like the following:
content do
order = case(params[:order])
when 'user_email_desc'
'email DESC'
when 'user_email_asc'
'email ASC'
else
nil
end
if(order.nil?)
users = User.all
else
users = User.order(order)
end
panel 'Users' do
section :priority => 1 do
table_for users, {:sortable => true, :class => 'index_table'} do
column('Email', :sortable => :user_email) {|user| user.email}
end
end
end
end