If you’re working with sorting large data sets in Rails, I’d usually recommend using something like the sorted gem to handle the work for you, but if you’re dealing with relatively small datasets, sometimes it’s just easier to roll your own helper.
I’m currently working on a project in which there are a small number of users in the system. Each has a first name, last name, email, and position column and I wanted to be able to easily sort the columns whenever a user clicks on the column header in each cell.
I needed a link to be generated based on a custom label, the query string, and the field on the model. The interface for the helper is simple
<%= link_to_by_order "Email Address", params, "email" %>
The corresponding helper method:
def link_to_by_order(text, params, criteria) if params[:direction] == "asc" link_to text, users_path(:order => criteria, :direction => "desc") else link_to text, users_path(:order => criteria, :direction => "asc") end end
Definitely not suitable for larger datasets but small to moderate with the appropriate indexes would yield decent performance.