Allow the sorting of ActiveRecord queries by model field names and arbitrary associations.
Add this to your gemfile:
gem 'query_sort_by_params', :github => "matzko/query_sort_by_params"
Set arbitrary sort parameters in your model:
class Widget < ActiveRecord::Base has_many :widget_owners has_many :owners, :through => :widget_owners sort_fields :owner_name => ->(query, direction) { query.joins(:owners).order("owners.name #{direction}") } end
Then you can use parameters to sort by that value:
Widget.sort_by_params({:sort_by => 'owner_name-desc'})
Or just use the fields already defined for the model:
Widget.sort_by_params({:sort_by => 'name-asc'})
You can set a default:
Widget.sort_by_params({:sort_by => 'name-asc'}, :default => ->(query) { query.order('created_at ASC') } )