< mockra >

Drag and Drop Lists - 14 Mar 2012

JQuery makes it easy to add sortable lists to your Rails application. You’ll want to add the following code to one of your CoffeeScript files.

jQuery ->
    update: ->
      $.post( $(this).attr( 'url' ), $(this).sortable 'serialize' )

Taking advantage of the Rails helper method, content_tag_for, makes it easy to pass the necessary information to our CoffeeScript. You can create a sortable list in your views with the following haml code:

%ul.sortable{ url: "#{sort_lists_url}" }
  - @lists.each do |list|
    = content_tag_for :li, list do
      = list.title

JQuery will then pass the IDs of our lists in the order they appear to the URL we specified in the url attribute on our sortable class, through params[:list]. We can then save the positions JQuery sends to the controller with the following code:

def sort
  params[:list].each_with_index do | list_id, index |
    List.update_all( { position: index }, { id: list_id } )

  render nothing: true