Sortable List in Ruby on Rails 3 Using jQuery

1. Go to Gamefile

gem "rails"
gem "mysql2"
gem "acts_as_list"

# go to console:
$ bundle install

Add acts_as_list to model

class Book < ActiveRecord::Base
  acts_as_list
end

add jquery to view and setup javascript content_for, Go to app/views/layouts/books.html.erb
Change this:

<%= javascript_include_tag :defaults %>

To this:

<%= javascript_include_tag "https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js", "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js", "rails.js" %>

Also before /body add:

<%= yield :javascript %>

edit index for li – tables don’t work

<h1>Listing books</h1>
<ul id="books"> <% @books.each do |book| %>
  <li id="book_<%= book.id %>"><span class="handle">[drag]</span><%= book.name %></li>
<% end %></ul>
<%= link_to 'New book', new_book_path %>

add javascript in view

# index.html.erb
<% content_for :javascript do %>
<%= javascript_tag do %>
// Sorting the list

$(document).ready(function(){
   $('#books').sortable({
       axis: 'y',
       dropOnEmpty: false,
       handle: '.handle',
       cursor: 'crosshair',
       items: 'li',
       opacity: 0.4,
       scroll: true,
       update: function(){
          $.ajax({
              type: 'post',
              data: $('#books').sortable('serialize'),
              dataType: 'script',
              complete: function(request){
                 $('#books').effect('highlight');
              },
                 url: '/books/sort'})
              }
          });
     });
 });
     <% end %>
<% end %>

and your controller

def index
   @books = Book.order('books.position ASC')
end

def sort
   @books = Book.all
   @books.each do |book|
   book.position = params['book'].index(book.id.to_s) + 1
   book.save
end

render :nothing => true
end

update your routes

root to: "books#index"
resources :books do
   post :sort, on: :collection
   # ruby 1.8 would go :on => :collection
end
Advertisements

About me
Interested about Ruby on Rails

One Response to Sortable List in Ruby on Rails 3 Using jQuery

  1. Maciej Stanczyk says:

    Greate job. Everything is clear. Thank you very much. You saved my day 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: