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
end
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 %>
<span>[drag]</span>
<%= 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])
end
render :nothing => true
end
That’s it. You have done.