在 Rails 应用程序中将产品添加到购物车时找不到 'id'= 的产品

Couldn't find Product with 'id'= when adding products to Cart in Rails app

当我尝试在我正在构建的应用程序中将产品添加到购物车时,我总是收到此错误 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 Cart按钮代码 从 :<%= 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

更新

这里是 link 到 github 回购 https://github.com/DadiHall/hlinreykdal

我已经通过 Active Admin 创建了所有产品,并且它应该可以正常工作。 我在这里错过了什么吗? 我不明白为什么这个错误不断出现。

问题出在以下代码行。

@product = Product.find(params[:product_id])

params[:product_id]nil 因为它不存在于 params 散列中。要了解 params 的含义,您可以这样做。

def create
  render text: params
end

现在,如果您尝试创建一个新的 product_item,您会发现传递给 create 操作的参数。

但是,如果您希望将 product_id 传递给 create 操作,则需要 nested 路由。

resources :products do
  resources :product_items
end

并将您的 html 更改为

<%= button_to product_product_items_path( @product) do %>
  <i class="fa fa-shopping-cart"></i>Add to Cart
<% end %>

您可以找到 运行 rake routes.

生成的路由

creation 动作的第二行,

@product_item = @cart.add_product(product.id)

我不确定 product 是什么。应该是

@product_item = @cart.add_product(@product.id)

?