商店中的UrlGenerationError #index

时间:2015-03-06 23:26:37

标签: ruby-on-rails routing

我遇到了我认为是路由错误的问题。我正在创建一个购物车,但不知怎的,我错过了所需的密钥[:product_id]。我相信可能是初学者错误而不是在某处放置正确的代码。

没有路由匹配{:action =>“add”,:controller =>“carts”,:product_id => nil}缺少必需的键:[:product_id]

app/views/stores/index.html.erb:34:in block in _app_views_stores_index_html_erb__2030225986820803304_70197415655620 app/views/stores/index.html.erb:3:in _app_views_stores_index_html_erb__2030225986820803304_70197415655620

Carts_Controller.rb

 class CartsController < ApplicationController
 def show
   cart_ids = $redis.smembers current_user_cart
   @cart_products = Product.find(cart_ids)
 end

 def add
   $redis.sadd current_user_cart, params[:product_id]
   render json: current_user.cart_count, status: 200
 end

 def remove
   $redis.srem current_user_cart, params[:product_id]
   render json: current_user.cart_count, status: 200
 end

 private

 def current_user_cart
  "cart#{current_user.id}"
 end

 def carts_params
  params.require(:cart).permit(:product_id)
 end
end

Cart.rb

 class Cart < ActiveRecord::Base
  belongs_to :user
 end

Products_Controller.rb

  class ProductsController < ApplicationController
  def index
   @products = Product.all
   @order_item = current_order.order_items.new
  end
 end

的routes.rb

  resource :cart, only: [:show] do
  put 'add/:product_id', to: 'carts#add', as: :add_to
  put 'remove/:product_id', to: 'carts#remove', as: :remove_from
  end

商店/ index.html中

 <%=link_to "", class: "button", data: {target: @cart_action, addUrl: add_to_cart_path(@product_id), removeUrl: remove_from_cart_path(@product_id)} do%>
  <%=@cart_action%>

1 个答案:

答案 0 :(得分:0)

当您执行add_to_cart_path(@product_id)时,它会将param发送为:id,您希望它为:product_id。

您可以通过以下两种方式解决此问题。

方式#1

在你的按钮/ link_to改变

add_to_cart_path(@product_id)

为:

add_to_cart_path(product_id:@product_id)

方式#2

您可以更新您的控制器和路由以期望并使用param id而不是product_id