2016-09-22 131 views
0

我正在尝试为我的物品添加“添加到购物车”方法。没有路线匹配[GET]

items_controller:

def to_cart 
    @item = Item.friendly.find(params[:id]) 
    @item.add_to_cart 
    redirect_to root_path 
end 

路线:

resources :items do 
    put :to_cart, on: :member 
end 

型号:

def add_to_cart 
    current_user.cart.items << self 
    current_user.cart.save 
end 

显示:

<%= @item.name %> 
<%= link_to 'add to cart', to_cart_item_path(@item) %> 

我得到了RoutingError:No route matches [GET] "/items/first/to_cart" '第一'因为友好的id。 我做错了什么?

+0

您可以将您的routes.rb?您需要在resources:items行添加'member::to_cart'。 –

回答

1

在您的链接添加method: :put默认情况下它是GET和Rails试图找到GET方法

<%= link_to 'add to cart', to_cart_item_path(@item), method: :put %> 
0

链接在网络上的路由只能发送GET请求。

要发送POST/PUT/PATCH/DELETE请求,您需要使用表单。

<%= form_for to_cart_item_path(@item), method: :put do |f| %> 
    <% f.submit 'Add to cart' %> 
<% end %> 

Rails为此提供了一个快捷方式button_to('add to cart', to_cart_item_path(@item))

Rails的UJS驱动程序(不显眼的JavaScript的驱动程序)还规定,在客户端创建一个表单时,该连接件有data-method属性的方法:

<%= link_to 'add to cart', to_cart_item_path(@item), method: :put %> 
+0

但是,如果你的方法是宁静的或正确使用HTTP动词的语义是非常有争议的。 PUT请求修改或替换现有资源。你在做什么是添加资源到购物车。不改变项目。这可能看起来微不足道,但是是一个非常重要的设计决定。 – max