Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# index.html.erb
<ul id="projects">
<% @projects.each_with_index do |project, index| %>
<% content_tag_for :li, project do %>
<%= project.name %>
<%= button_to('up', :action => 'sort', :projects => @projects.swap(index, index -1)) if index > 0 %>
<%= button_to('down', :action => 'sort', :projects => @projects.swap(index, index +1)) if index < @projects.length - 1 %>
<% end %>
<% end %>
</ul>
#projects_controller.rb
def sort
params[:projects].each_with_index do |id, index|
Project.update_all(['position=?', index+1], ['id=?', id])
end
redirect_to projects_path
end
# application_controller.rb
class Array
def swap(a,b)
swapped = self.clone
swapped[a], swapped[b] = self[b], self[a]
swapped
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.