Monday, May 11, 2009

Rails plugin/gem to sort nested set trees using drag-n-drop

A Rails app I'm working on needs to handle a fairly big tree of active record models. For this I use a nested set implementation in the models.

Displaying parts of of the tree in my views was of course a piece of cake and fairly fast thanks to the way nested sets in the database works.
If you need a refresher on the db theory you can google on "nested set" or take a look at this article. Or maybe this article that believe was the first one from back in the nineties. The interesting stuff starts at the "Trees in SQL" section.

Anyway, trouble struck when I wanted to implement a drag-n-drop sort/rearrange feature using the sortable_element script.aculo.us helper that comes with Rails.

The default behavior of this helper is to send the the complete tree of id:s to the server when you "drop" your dragged item where you want it. This tree then reflects the how the new tree should look.
Needless to say this is a bit more information than required when you want to update your nested set model. In your controller your only need is to find out what was moved and where did it end up.

Parsing the tree sent in the request parameter and comparing it to the database isn't an option if you have a very large tree and worry about speed. So I created a plugin, SortableElementForNestedSet, that helps you find the answers the what and where questions and you'll find the first version of it on GitHub.

Installation and simple usage instructions are found in the readme. Enjoy!

Nested set implementation for Rails:

No comments:

Post a Comment