How to allow your user to sort your list differently?

Posted by tom February 19th, 2006

So you’ve generated your scaffolding code and would like to allow the user to sort your list differently. If you add a little code to the generated scaffolding code, you’re there.

Let’s say I have an “Item” model and all the scaffolding code for “Item”:
ruby script/generate model item
ruby script/generate scaffold item
It starts with adding a new method in the items_controller.rb:

  def list_by_priority
    @item_pages, @items = paginate :items, :per_page => 10, :order_by => “priority, due_date” 
    render_action ‘list’
  end

This code is very similar to the already present list method, but has a different order_by symbol.

Now add a bit of code to your view:
 <th><%= link_to "priority", { :action => "list_by_priority" }, "alt" => "Sort by Priority" %></th>

This code will call your controller’s list_by_priority method. This method will render the action ‘list’, as we did not create a list_by_priority view, which we also don’t want.

Leave a Reply