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.
First…
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
DESC”}
sorthash.default = “column1, updated_at”
sort = params[:sort] || session[:model][:sort]
session[:model][:sort]=sort
@model_pages, @models = paginate :model, :per_page => 10,
:order=>sorthash[sort]
end
=== 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.