Rails ajax:无法加载资源:服务器响应状态为404(未找到)

时间:2014-03-29 22:04:14

标签: javascript jquery ruby-on-rails ajax

我尝试使用ajax在我的应用中重写一些操作。

items_controller:

...
def add_to_cart
  @cart = Cart.where(id: session[:cart_id]).first
  @cart = Cart.create if @cart.nil?
  session[:cart_id] = @cart.id
  session[:cart_items] = @cart.items
  session[:cart_items] << @item
  redirect_to root_url
end
...

items.js:

jQuery(function($) {
  $(".addtoCart").click( function() {
    var current_item = $(this).parents('tr')[0];
    if(confirm("Add to cart")) {
      $.ajax({
        url: '/items/' + $(current_item).attr('data-item-id') + '/add_to_cart',
        type: 'POST'
      });
    };
  });
});

查看文件:

%tr{"data-item-id" => "#{i.id}"}
  %td
    %span.addtoCart Add to cart

路线:

Store::Application.routes.draw do

  root 'items#index'

  resources :items

  resources :items do
    get :add_to_cart, on: :member
  end

end

当我点击Add to cart时,虽然存在Failed to load resource: the server responded with a status of 404 (Not Found),但仍有POST http://localhost:3000/items/13/add_to_cart 404 (Not Found)/items/13错误。我在哪里弄错了?

错误堆栈跟踪:

Started POST "/items/13/add_to_cart" for 127.0.0.1 at 2014-03-30 02:55:03 +0400

ActionController::RoutingError (No route matches [POST] "/items/13/add_to_cart")

谢谢!

1 个答案:

答案 0 :(得分:0)

更改您的路线如下:

  root 'items#index'

  resources :items do
    post :add_to_cart, on: :member
  end

我将add_to_cart请求转换为post而不是get,因为您正在触发post请求,并将路由定义为get。 此外,我删除了定义resources :items

的重复路由