I just wrote some sortable code for a Rails/jQuery app and figured I would blog just how little code it takes, and also the single MySQL query I used on the backend.
I have a #images div containing several .image divs. I want the .image divs to be drag-and-drop sortable, and for the ordering to be persisted to the database (in a column named “ordinal”).
The JavaScript sorting, using Sortables from jQuery UI:
1 2 3 | |
So my .image divs are sortable within their containing #images, and can only be dragged on the y axis (up and down). When the sorting is done, an Ajax request is sent to /admin/images/sort. The AUTH_TOKEN bit is Rails CSRF protection – see this post for more details and another way of handling it.
The Ajax request contains params like image[]=3&image[]=1&image[]=2, reflecting the order. The parameter name and values are taken from the element ids (e.g. “image_1”).
I route the path:
1
| |
Then make a controller action:
1 2 3 4 5 | |
What’s rendered isn’t important, but you should render something or you get a 404.
The model method is just this:
1 2 3 4 5 6 7 | |
This generates a query like
1
| |
which sets the ordinal column to the position of the record id in that set.
Whenever I need the images ordered, I just make sure they’re sorted by ordinal ASC, created_at ASC.
That’s all the code it takes.