[英]No route matches [GET]
I'm trying to add 'add to cart' method for my items. 我正在尝试为商品添加“添加到购物车”方法。
items_controller: items_controller:
def to_cart
@item = Item.friendly.find(params[:id])
@item.add_to_cart
redirect_to root_path
end
routes: 路线:
resources :items do
put :to_cart, on: :member
end
model: 模型:
def add_to_cart
current_user.cart.items << self
current_user.cart.save
end
show: 节目:
<%= @item.name %>
<%= link_to 'add to cart', to_cart_item_path(@item) %>
I got RoutingError: No route matches [GET] "/items/first/to_cart"
'first' because of friendly id. 我收到RoutingError:由于友好ID,
No route matches [GET] "/items/first/to_cart"
'first'。 What I did wrong? 我做错了什么?
添加method: :put
默认情况下,在您的链接中输入method: :put
是GET
而Rails尝试使用GET
方法查找路线
<%= link_to 'add to cart', to_cart_item_path(@item), method: :put %>
Links on the web only send GET requests. 网络上的链接仅发送GET请求。
To send a POST/PUT/PATCH/DELETE
request you need to use a form. 要发送
POST/PUT/PATCH/DELETE
请求,您需要使用表格。
<%= form_for to_cart_item_path(@item), method: :put do |f| %>
<% f.submit 'Add to cart' %>
<% end %>
Rails provides a shortcut for this button_to( 'add to cart', to_cart_item_path(@item) )
. Rails提供了此
button_to( 'add to cart', to_cart_item_path(@item) )
的快捷方式。
The Rails UJS driver (unobtrusive javascript driver) also provides a method that creates a form in the client when the link element has the data-method
attribute: Rails UJS驱动程序(非干扰性javascript驱动程序)还提供了一种方法,当link元素具有
data-method
属性时,该方法可在客户端中创建表单:
<%= link_to 'add to cart', to_cart_item_path(@item), method: :put %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.