Module | SortHelper |
In: |
sort_helper.rb
|
Author: Dave Burt dave@burt.id.au
Version: 17 Feb 2005
Makes column headings users can click to define how the table is sorted.
<tr> <th><%= link_to_sort_by 'First Name', 'name' %></th> <th><%= link_to_sort_by 'Surname', 'family.name' %></th> <th><%= link_to_sort_by 'Email', 'email' %></th> </tr>
helper :sort def list # action SortHelper.columns = %w[ name family.name email ] SortHelper.default_order = %w[family.name name] @people = Person.find_all.sort do |a, b| SortHelper.sort(a, b, @params) end end
Set the columns that may be used to sort by. You must set this from the controller before you can use link_to_sort_by in a view.
This is a comparison method that returns -1, 0 or 1 depending on the passed objects a and b, and the sorting priorities defined in params. It can be used in blocks given to +Enumerable#sort+.
Use it like this:
@people = Person.find_all.sort do |a, b| SortHelper.sort(a, b, @params) end
Create a link (‘a’ tag) back to the current action, but sorting by sort_column before any existing ordering.
Example: On an un-sorted page,
<%= link_to_sort_by 'First Name', 'name' %> <%= link_to_sort_by 'Surname', 'family.name' %> <%= link_to_sort_by 'Email', 'email' %>
could result in:
<a href="/person/list?sort=1">First Name</a> <a href="/person/list?sort=2">Surname</a> <a href="/person/list?sort=3">Email</a>
If the page was already sorted by first name,
<%= link_to_sort_by 'First Name', 'name' %> <%= link_to_sort_by 'Surname', 'family.name' %> <%= link_to_sort_by 'Email', 'email' %>
could result in:
<a href="/person/list?sort=-1">First Name</a> <a href="/person/list?sort=2+1">Surname</a> <a href="/person/list?sort=3+1">Email</a>