使用coffeescript + rails3进行Ajax更新

时间:2012-11-28 10:52:36

标签: ruby-on-rails-3 routing coffeescript

我正在关注here中的可排序列表教程,但不幸的是这篇文章有点旧(但非常有用),并且在尝试使用

实现它时遇到了一些问题
Rails 3.2.x
coffeescript 
Jquery

我的问题是,视图没有将请求传递给控制器​​而是给出了路由错误

以下是我的观点

#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 %>

这是我的coffeescript

#books.js.coffee
jQuery ->
  $('#books').sortable
    axis: 'y'
    handle: '.handle'
    update: ->
      $.post($(this).data('#books'), $(this).sortable('serialize'))

这是我的控制器

#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

这是我的路线

#config/routes.rb
resources :books do
  collection do 
    post :sort  
  end
end

这是我得到的错误

在2012-11-28 16:13:29 +0530开始发布“/ undefined”for 127.0.0.1

ActionController::RoutingError (No route matches [POST] "/undefined"):
  actionpack (3.2.9) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
  actionpack (3.2.9) lib/action_dispatch/middleware/show_exceptions.rb:56:in `call'
  railties (3.2.9) lib/rails/rack/logger.rb:32:in `call_app'
  railties (3.2.9) lib/rails/rack/logger.rb:16:in `block in call'
  activesupport (3.2.9) lib/active_support/tagged_logging.rb:22:in `tagged'
  railties (3.2.9) lib/rails/rack/logger.rb:16:in `call'
  actionpack (3.2.9) lib/action_dispatch/middleware/request_id.rb:22:in `call'
  rack (1.4.1) lib/rack/methodoverride.rb:21:in `call'
  rack (1.4.1) lib/rack/runtime.rb:17:in `call'
  activesupport (3.2.9) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
  rack (1.4.1) lib/rack/lock.rb:15:in `call'
  actionpack (3.2.9) lib/action_dispatch/middleware/static.rb:62:in `call'
  railties (3.2.9) lib/rails/engine.rb:479:in `call'
  railties (3.2.9) lib/rails/application.rb:223:in `call'
  rack (1.4.1) lib/rack/content_length.rb:14:in `call'
  railties (3.2.9) lib/rails/rack/log_tailer.rb:17:in `call'
  rack (1.4.1) lib/rack/handler/webrick.rb:59:in `service'
  /home/sameera/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/webrick/httpserver.rb:111:in `service'
  /home/sameera/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/webrick/httpserver.rb:70:in `run'
  /home/sameera/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/webrick/server.rb:183:in `block in start_thread'


  Rendered /home/sameera/.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.2.9/lib/action_dispatch/middleware/templates/rescues/routing_error.erb within rescues/layout (0.7ms)

非常感谢任何帮助,

谢谢

1 个答案:

答案 0 :(得分:0)

我相信$.post需要url这样的参数:

$.post('/books/sort', $(this).data('#books'), $(this).sortable('serialize'))