User defined sorting of ActiveRecord queries for Rails
Add this line to your application's Gemfile:
And then execute:
$ bundle install
- Include the gem in the controller you wish to be sortable
class UsersController < ApplicationController include Orderable2 [...] end
- Order your collection using the
class UsersController < ApplicationController include Orderable2 def index @users = User.all.order(sort_order) end end
This uses the order provided in the params or falls back to ordering by ascending ID if no order parameter is present in the request.
You can also override the default order in the sort_order call:
class UsersController < ApplicationController include Orderable2 def index @users = User.all.order(sort_order(email: :asc, id: :asc)) end end
This would sort by ascending email and ascending ID if no ordering params are present in the request.
To set the ordering using request parameters, set a parameter named
order containing a sorting definition in the following format:
Multiple columns may be defined by separating them by comma:
So, to create a link that sorts users by country, you could use the following
Orderable2 includes view helpers that simplify usage in the views.
In order to print the label of a table column or filter, use the following helper
<%= orderable_for :country %>
This automatically creates the necessary label and displays the current sort order using ↑ or ↓. Clicking on the label reorders by that column.
By default, the helper lets you sort by multiple columns, for example username ASC, country DESC. If you wish to disable this behaviour and only allow sorting based on a single column, use the
<%= orderable_for :country, single: true %>
Bug reports and pull requests are welcome on GitHub at https://github.com/code-fabrik/orderable2.
The gem is available as open source under the terms of the MIT License.