Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrrooijen/168431 to your computer and use it in GitHub Desktop.
Save mrrooijen/168431 to your computer and use it in GitHub Desktop.
# 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