每当我尝试从商品的显示页面添加商品到购物车时,我一直收到以下路由错误:* * ActionController::RoutingError(没有与[GET] "/order_items "匹配的路由)**.在控制台上检查时,没有项目添加到购物车。
- 路由. rb**
Rails.application.routes.draw do
devise_for :users
root to: 'articles#index'
resources :articles, except: [:destroy]
resources :order_items, only: [:create]
resources :orders do
get '/current', to: 'orders#current', on: :collection
resources :checkout, only: [:create]
end
end
- 订单_项目. rb**
class OrderItem < ApplicationRecord
belongs_to :order
belongs_to :article
end
- 铁路路线**
order_items POST /order_items(.:format) order_items#create
- 订单物料控制器. rb**
class OrderItemsController < ApplicationController
before_action :authenticate_user!
def create
order_item = current_order.order_items.new(article_id: params[:article_id])
if order_item.save
redirect_to root_path, notice: 'Successfully added to cart.'
else
redirect_to root_path, alert: 'Error adding to cart.'
end
end
def current_order
order = Order.where(user_id: current_user.id, status: 'created').order(updated_at: :desc).last
order || Order.create(user_id: current_user.id)
end
end
- 显示. html. erb**
<% if user_signed_in? %>
<%= link_to 'Add to cart', order_items_path(article_id: params[:id]), method: :post %>
<% else %>
<%= link_to 'Log In', new_user_session_path , class: "text-blue-500" %>
<% end %>
1条答案
按热度按时间hs1ihplo1#
为什么?你只是在创造路线
resources :order_items, only: [:create]
所以你只得到POST路径。你要求GET路径。所以你的错误。正如所指出的
button_to
将工作。你的link_to
表单不工作的原因是它试图在发出POST请求之前检索order_items
路径。除非另有说明,否则button_to
默认为POST动词。