How to do Ajax style drag-n-drop sorting with Rails

Here is a quick tutorial on how to do this. The “secret” or easy solution is to use Rails “acts_as_list” plugin.

1. Install the “acts_as_list” plugin that is going to be used for this. With Rails 2.0+, the plugin is no longer part of Rails core, so you will need to do “ruby script/plugin install acts_as_list”.

2. You need to define/add a “position :integer” column to your model that is to be sorted on.

3. Insert the “acts_as_list” directive/declaration in your sortable model, such as:

 
class FoodItem <ActiveRecord::Base
  belongs_to :grocery_list
  acts_as_list :scope => :grocery_list
end

The “:scope” parameter just tells acts_as_list plugin to sort items within the scope of its owner, in this case, within the same grocery_list. In your code, this could be just user, or owner of the stuff you want to sort on.

Next few steps are about how you implement the views to allow users to drag-n-drop sort the list.

4. Define a <ul></ul> section in your view that is going to be used for the dnd sorting:

<ul id="grocery-list" style="cursor: move">
  <% @grocery_list.food_items.each do |f| %>
    <li id="item_<%= f.id %>">
      <%= f.name %>
    </li>
  <% end %>
</ul>

In this example, pay close attention to the tag “id”s, those id values are important for acts_as_list plugin to work its magic.

5. Add following code to your view, same view where the “ul” tag is in:

<%= sortable_element "grocery-list",
:url => {:action => "sort", :id => @grocery_list},
:complete => visual_effect(:highlight, "grocery-list")
%>

What this does is that it generates all needed javascript to make your “ul” list sortable with drag-n-drop, and it reports back your server code with new position information through the :url parameters.

6. Define a backend action to update your model with new position data, such as:

def sort
@grocery_list = GroceryList.find(params[:id])
@grocery_list.food_items.each do | f |
f.position = params["grocery-list"].index(f.id.to_s)+1

f.save
end
end

Then you’re all done.

BTW, I learned this trick from a book called “Rails Recipes”, where there’s more good stuff like this. Check it out if you haven’t.

Have a nice weekend!

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay
Harry Che has written 1 articles for us. Website:http://www.goalsontrack.com
The information provided is for educational purposes only. All content including links and comments is provided "as is" with no warranty, expressed or implied. Use is at your own risk and you are solely responsible for what you do with it.

No Comments

Leave a reply