Drag & Drop Functionality for sorting a list on Ruby On Rails…

There is an easy way of implementing drag and drop sorting functionality in RoR with the help of ‘dragdrop.js’. Here is the steps :-

Consider i’m dealing with the movie application, and having a list of scenes(table named ‘scenes’) for a movie.

First gather the list of scenes in controller :- (scenes_controller.rb)

def list
@scenes=Scene.find :all

Note : For doing this sorting you need to have a field named ‘position’ in the appropriate table. for eg, here i have a ‘position'(integer type) field in ‘scenes’ table.

Include your drag and drop script file either in view file (list.html.erb) or in your layout
<%= javascript_include_tag ‘dragdrop.js’ %>

In view file :- (list.html.erb)

<% for scene in @scenes %>
<%= scene.scene_title %><br /><br />
<% end %>
<%= sortable_element(“scenes”, :url => sort_scenes_path, :handle => “handle”) %>

Note : Here ‘scenes’ is the name of the params to be passed, and sort_scenes_path will go to the method named ‘sort’ on scenes_controller.rb

Back in controller :- (scenes_controller.rb)

def sort
params[:scenes].each_with_index do |id, index|
Scene.update_all([‘position=?’, index+1], [‘id=?’, id])
render :nothing => true

That’s it. You have done.


3 thoughts on “Drag & Drop Functionality for sorting a list on Ruby On Rails…”

  1. HI Selva!
    This is a great solution to the problem of sorting in rails. I assume, that you have to have a field called position in the database for the model you want to sort that way, right?
    How can I define, where the user can drag with the mouse? How do I define the range? Does it have to be -Tag? Or can I use a instead?


    1. You can have any tags, like span, div, a, ul & li etc.., For example, if you have a set of li tags within ul and mention the id of li tag as a sortable element, then you can sort those items inside your li anywhere within that ul.

Comments are closed.