2016-09-22 272 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