Draggable, sortable, editable list with jQuery and Rails3.1
Suppose you wanted to allow your customers to create a list of items that are both editable and sortable. Customers should be able to sort the items by dragging them into the correct position. Customers should also be able to delete an item, and add a new item.
Yikes! Sounds like a lot of fancy UI. Thankfully, with the help of Rails 3.1 and jQuery-UI, it’s actually not that much code.
Let’s suppose that this list was used to define a custom workflow. Something like the following:
Here’s how we do it…
First, we’ll start with the models. A Workflow has many WorkflowStates. Each WorkflowState has a name (or “label”) and a position. The position attribute is used to preserve the relative ordering of the states. Note that we define an
:order in the
:has_many relationship, and we specify that Workflow
accepts_nested_attributes for WorkflowStates.
Next comes the form and it’s controller. Note that we:
- Explicitly include an
inputfor the id of the WorkflowState. Rails will provide this automatically if you don’t… but it will also stick it outside the
<li>. This will confuse the jQuery layer (coming soon).
_destroyfield is rendered as a hidden field, rather then the suggested checkbox. This allows us to provide the destroy functionality with a much more intuitive UI.
Finally, we layer on the jQuery goodness. This layer is responsible for
- Making each input element draggable.
- Keeping the
positioninput elements in the form up to date.
- Providing the add and delete and element features
Posted by cailinanne