I’m trying to implement a sorting list with Rails3 and coffeescript. I had a routing issue earlier and was able to solve it with your generous help, so now I have a different issue, My data parameter is not passing to the server,
Following is my view
#index.html.erb
<h1>Listing books</h1>
<ul id="books"> <% @books.each do |book| %>
<li class="book<%= book.id %>"><span class="handle">[drag]</span><%= book.name %></li>
<% end %></ul>
<%= link_to 'New book', new_book_path %>
following is my books.js.coffee file
jQuery ->
$('#books').sortable
axis: 'y'
handle: '.handle'
update: ->
$.post('/books/sort', $(this).data('#books'), $(this).sortable('serialize'))
Following is my controller
#books_controller.rb
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
this is the error I’m getting
Served asset /jquery.js - 304 Not Modified (0ms)
Started POST "/books/sort" for 127.0.0.1 at 2012-11-28 17:03:25 +0530
Processing by BooksController#sort as */*
Book Load (0.2ms) SELECT "books".* FROM "books"
Completed 500 Internal Server Error in 2ms
NoMethodError (undefined method `index' for nil:NilClass):
app/controllers/books_controller.rb:14:in `block in sort'
app/controllers/books_controller.rb:13:in `each'
app/controllers/books_controller.rb:13:in `sort'
Rendered /home/sameera/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.2.9/lib/action_dispatch/middleware/templates/rescues/_trace.erb (40.8ms)
Rendered /home/sameera/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.2.9/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.0ms)
Rendered /home/sameera/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.2.9/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (47.7ms)
So when i say p params, I get {"action"=>"sort", "controller"=>"books"}, So it doesnt have a param called ‘book’ and hence gives a nil error, can someone help me out,
any help will be greatly appreciated
thanks in advance
You have a couple things going wrong here. First of all, your
$.postarguments are a bit confused:$.postwants the data in the second argument so just this:makes more sense.
Sortable’s
serializemethod wants DOMidattributes to be in a specific form:In your Rails controller, you want an array of book IDs in
params[:book]so you wantbook[]=id&book[]=id&...going to your server. That means that you want your<li>s to look more like this:Or you could keep use
classattributes by including an underscore:and then telling
serializeto look atclass:You should also use the
expressionoption and leave the HTML alone:There are a few other ways to arrange things, see the sortable documentation for further details.