Reputation: 5590
In an active admin show page, I've got two panels, the first being the primary record, the second being associated info (by has_many) so show
looks like this:
panel "Max Amount" do
table_for user.max_amount do
column 'Amount', :amount
column 'time', :updated_at
end
end
Can i sort this high-to-low (or low-to-high) on the amount column?
Update: I found the source for the demo ( https://github.com/gregbell/demo.activeadmin.info/blob/master/app/admin/users.rb ) which seems to have sorting but when you go to the actual demo site it's not working. Is this feature perhaps broken? Is there a work-around?
Upvotes: 15
Views: 8640
Reputation: 798
Expanding on the accepted Answer
I would recommend a more "universal" solution:
The problem comes from column_names with underscore _
character or needing to sort on nested attribute values as pointed out in this Question. The order argument needs to have the associated table name, which may contain an underscore _
character as well. This solution fails when that happens.
However, a minor change solves for this case and can be used in either case:
Quote.order(params[:order].gsub('_', ' ')
becomes, as suggested and explained by this Answer
Quote.order(params[:order].sub(/.*\K_/, " ")
panel "P&L" do
table_for Quote.order(params[:order].sub(/.*\K_/, " ")), sortable: true do
column("Revenue", sortable: :revenue) { |quote| number_to_currency quote.revenue }
column("Profit", sortable: :profit) { |quote| number_to_currency quote.profit }
end
end
If you wish to avoid regexps then I recommend looking at other solutions to this Question that fits your needs.
Upvotes: 0
Reputation: 5135
ActiveAdmin now supports table sorting.
table_for ride.bookings.order('updated_at desc') do
column :name
column :created_at
end
This, thanks to Ryan Bates's screencast: http://railscasts.com/episodes/284-active-admin?view=asciicast
Upvotes: 4
Reputation: 5784
With rails 4.2, based on @idrinkpabst, I did the following:
table_for group.devices.order(
# Support for column name with underscore
# Support "no sort param"
(params[:order] ? params[:order] : '').gsub('_asc', ' asc').gsub('_desc', ' desc')
), sortable: true do
# Directly using symboles and not using sortable:
column :presence
column :serial_number
column :apk_version
column :firmware_version
end
It's a more robust version:
Upvotes: 8
Reputation: 1838
The only way I found to do it was a bit hacky. ActiveAdmin will pass in the column name and asc/desc via the params hash, then you can add that to your query.
Also, make sure to pass "sortable: true" into the table_for call.
panel "P&L" do
table_for Quote.order(params[:order].gsub('_', ' ')), sortable: true do
column("Revenue", sortable: :revenue) { |quote| number_to_currency quote.revenue }
column("Profit", sortable: :profit) { |quote| number_to_currency quote.profit }
end
end
Upvotes: 17