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

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 "", "", "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_<%= %>"><span class="handle">[drag]</span><%= %></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

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

and your controller

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

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

render :nothing => true

update your routes

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

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: Logo

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: