Drag and Drop Sorting with JQuery and Rails

I decided to switch to JQuery recently, and I've been enjoying it. Part of the fun is trying out all the plugins that are available. :) This past week I needed to do drag and drop reordering for the first time since moving over to JQuery, so I thought I'd share some of the code that makes this really easy.

With Prototype, you can use the javascript that comes with the Rails distribution, but for this case I decided to go with the Table Drag and Drop JQuery plugin, as it had the right combination of functionality and ease of use. Once the plugin is in your project, getting a sortable table is very simple.

First up is the view, with the javascript injected into the head section of the document by using content_for. You'll note that for this simplified example an unordered list actually would have been better than a table, but in the original app I wanted to use a table for this list of items, so I wanted to make sure to use a plugin that supported that.

After creating the table, we simply use the document ready event to add some behavior to it. The plugin serializes the ids of the table rows in an array and sends that array, named after the table id, as a parameter to the controller. I add the authenticity token to the parameters sent via AJAX, and if the action was successful I just pop up an alert.

The controller iterates over all the specifications, checking the position in the db (see the acts_as_list plugin) versus the position in the array that was sent in the request. For the items that are affected, it updates the position in the db. Since we are only calling this action via AJAX, we just render nothing and indicate a successful status.

Of course there are few bits you can pretty up, both in the view and the controller, but that's the basic approach. Fast, easy, and client-approved. :)