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)
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
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)
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.