Ruby on Rails: How to provide a list of elements that can be sorted


No special preparation is required.


It is assumed only that your database has a table of items with identifiers and an integer column in which to record the sort order. This cannot, of course, be the identifying column. In this example, the table is items and the column is priority.


No changes to models are required


You must include the JavaScript libraries in the view. This is done with the following line:

<%= javascript_include_tag :defaults %>

The view should render a partial which will contain the items to be sorted.

<%= render :partial => ‘items’ %>

In the partial, there should be an identified container for all the items (<div id="items"> below). Each item should also be in a container with a unique ID. (It is possible to use containers other than <div> and other IDs, but the ID must end with an underscore and the actual element ID.)

<div id=”items”>
<% for item in @items %>
		<div id=”id_<%= %>”>
			<%= %>
<% end %>
<%= sortable_element(“items”, :tag => ‘div’, :update => ‘items’, :url => {:action => ‘reorder’}) %>
</div><!-- items -->


The controller should include an action named in the view. In this case, it is reorder. The action should reorder the items based on the provided parameters and then re-render the partial.

def reorder
	@neworder = params[:items]

	@neworder.each_with_index { |id, priority|
		item = Item.find(id)
		item.priority = priority

	@items = Item.find(:all, :order => “priority ASC”)
	render :partial => ‘items’

Tags: Technical

Updated at: 3 December 2008 12:12 AM