Semi-Dynamic table sorting (without AJAX)

In a previous thread some people were interested in ways to sort a
table. I mentioned a simple method for doing so by using links in the
titles. Having actually tried to implement this strategy, I have come
across several refinements that I would like to share.


your table view should look like this…

<%= link_to 'Column1', :sort=>'column1' %> <%= link_to 'Column2', :sort=>'column2' %>

your ‘model’ controller ‘list’ action should look like this…

def list
sorthash = {“column1”=>“column1, updated_at”, “column2”=>“column2
sorthash.default = “column1, updated_at”
sort = params[:sort] || session[:model][:sort]
@model_pages, @models = paginate :model, :per_page => 10,

=== What this does ===

The view passes a hash key as the :sort parameter. This gets looked up
in the sorthash, which returns the actual columns needed to sort. That
gets passed to the paginator.

Key features…

  • the sort order gets saved in the session, so the view will remember
    the sort order until the user logs off. Without this, even switching to
    another page will cause the view to forget the sort order.

  • by putting the valid sort orders into a hash and defining a default
    sort order, we avoid the risk that a malicious user can inject SQL into
    the paginator. It also keeps the view code prettier.

  • all the sorting is done by the database, so this puts more strain on
    the server. It also causes a page refresh, which can be annoying. It
    does not require javascript to work.

A similar technique can be used to ‘filter’ the view.

Any comments, feedback, tweaks, etc… would be appreciated.

Any comments, feedback, tweaks, etc… would be appreciated.

I like that implementation… thanks for the snippet. :slight_smile:

On 4/16/06, Christian K. [email protected] wrote:

I tried it a couple months ago and had issues with pagination.

When I went to the second page the sort order was lost.

I did not try to resolve it. I was a definate newbie at that point.


Greg F.
The Norcross Group
Forensics for the 21st Century

The trick for this method is to store the persistent information in the
session store so that you can reload it on the next page.

I have since moved to a similar (and cleaner) method that doesn’t use
the session store as much. I’ll try to write up an article about this
soon after things settle down at work.

On Monday, April 17, 2006, at 8:25 AM, Greg F. wrote:
Greg F.
The Norcross Group
Forensics for the 21st Century

Rails mailing list
[email protected]


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs