【发布时间】:2017-01-04 22:20:40
【问题描述】:
当我尝试将产品添加到我正在构建的应用程序中的购物车时,我总是收到此错误 Couldn't find Product with 'id'= 。根据 Better Errors,这发生在我的 product_items_controller.rb 的 Create 方法的第一行,如下所示。
def create
@product = Product.find(params[:product_id])
@product_item = @cart.add_product(product.id)
if @product_item.save
redirect_to root_url, notice:'Product added to Cart'
else
render :new
end
end
我将第一行更改为:@product = Product.find(params[:id]),但这并没有纠正错误。
今晚早些时候我修改了Add to Cartbutton 代码
从 :<%= button_to product_items_path(product_id: product) do %> 到 <%= button_to product_items_path( @product) do %>
这是现在添加到购物车按钮的代码。
<%= button_to product_items_path( @product) do %>
<i class="fa fa-shopping-cart"></i>Add to Cart
<% end %>
更新,添加 ROUTES.rb
这里是 routes.rb
Rails.application.routes.draw do
resources :categories
resources :labels
resources :products
resources :carts
resources :product_items
resources :orders
devise_for :admin_users, ActiveAdmin::Devise.config
ActiveAdmin.routes(self)
root 'pages#index'
end
另一个编辑
这里是 cart.rb,它拥有 add_product 方法
class Cart < ActiveRecord::Base
has_many :product_items, dependent: :destroy
def add_product(product_id)
current_item = product_items.find_by(product_id: product_id)
if current_item
current_item.quantity += 1
else
current_item = product_items.build(product_id: product_id)
end
current_item
end
def total_price_usd
product_items.to_a.sum{|item| item.total_price_usd}
end
def total_price_isl
product_items.to_a.sum{|item| item.total_price_isl}
end
end
更新
这里是github repo的链接https://github.com/DadiHall/hlinreykdal
我已经通过 Active Admin 创建了所有产品,并且工作正常。 我在这里错过了什么吗? 我不明白为什么这个错误不断出现。
【问题讨论】:
-
路由
product_items_path( @product)映射到哪个动作?你能发布你的routes.rb吗?@cart和product在create操作中是什么? -
嗨,我已经添加了 routes.rb 和 cart.rb.... add_product 方法在 cart.rb 中
-
createaction 第二行中的product是什么? -
这是商品的id
-
也许您想查看 GitHub 存储库,我添加了问题的链接
标签: ruby-on-rails ruby ruby-on-rails-4 shopping-cart