问题
Active Admin doesn't seem to support multiple columns sorting yet (i.e. pass multiple values to the config.sortable
option).
I saw an old monkey patch here but it doesn't seem to work with my version (1.0.0.pre from Github).
Is there any way to get multiple sortable columns on the latest Active Admin version?
回答1:
This is also a monkey patch:
Create a new file in config/initializers or in the lib folder: multiple_columns_sorting.rb
module ActiveAdmin
class ResourceController < BaseController
module DataAccess
def apply_sorting(chain)
params[:order] ||= active_admin_config.sort_order
orders = []
params[:order].split('_and_').each do |fragment|
order_clause = OrderClause.new fragment
if order_clause.valid?
orders << order_clause.to_sql(active_admin_config)
end
end
if orders.empty?
chain
else
chain.reorder(orders.shift).order(orders)
end
end
end
end
end
Restart the server. Now you can use several columns name separeted by "_and_"
. For example:
config.sort_order = 'first_name_desc_and_last_name_asc'
回答2:
For ActiveAdmin v0.6.0, I tweaked the monkey patch to something like this
# initializers/active_admin.rb
module ActiveAdmin
class ResourceController
module DataAccess
def apply_sorting(chain)
params[:order] ||= active_admin_config.sort_order
orders = []
params[:order].present? && params[:order].split(/\s*,\s*/).each do |fragment|
fragment =~ /^([\w\_\.]+)_(desc|asc)$/
column = $1
order = $2
table = active_admin_config.resource_column_names.include?(column) ? active_admin_config.resource_table_name : nil
table_column = (column =~ /\./) ? column :
[table, active_admin_config.resource_quoted_column_name(column)].compact.join(".")
orders << "#{table_column} #{order}"
end
if orders.empty?
chain
else
chain.reorder(orders.shift).order(orders)
end
end
end
end
end
For my case, I would use it as following as it's more natural to me:
config.sort_order = 'first_name_desc, last_name_asc'
The details are from my gist https://gist.github.com/anhkind/5e9d849ebe4f3a452e31
回答3:
Well if its just 1 or 2 fields you want to update, then you can do it like this. In your Active Admin Controller just use this method. This method over uses first_name and last_name column for sorting, when you pass full_name for sorting.
def apply_sorting(chain)
params[:order] ||= active_admin_config.sort_order
order_clause = ActiveAdmin::OrderClause.new params[:order]
if order_clause.field == 'full_name'
chain.reorder("(first_name, last_name) #{order_clause.order}")
else
super
end
end
回答4:
You can add something like this
ActiveAdmin.register Model do
controller do
def scoped_collection
Model.order('field_1 DESC, field2 ASC')
end
end
config.sort_order = ''
end
来源:https://stackoverflow.com/questions/24672758/active-admin-sorting-on-multiple-columns