#<#<Class:0x007fe77c4f3c68>:0x007fe77c69cb78> 的未定义局部变量或方法“product”

undefined local variable or method `product' for #<#<Class:0x007fe77c4f3c68>:0x007fe77c69cb78>

我在构建应用程序时遇到问题。

products/show.html.erb 我有这个代码可以将产品添加到购物车。

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

它总是给我这个错误 undefined local variable or method 'product' for #<#<Class:0x007fe77c4f3c68>:0x007fe77c69cb78> 根据 Better Error gem

,此错误发生在第一行

我正在使用 ActiveAdmin,但我很确定错误不会因此而出现。

我不确定为什么会这样,对我来说代码似乎不错,但我一定是在监督某些事情。

如果有人能看一看,也许能看到我看不到的东西,那就太好了。

这是`ProductItemsController.rb``

class ProductItemsController < ApplicationController

include CurrentCart

before_action :set_cart, only: [:create]
before_action :set_product_item, only: [:show, :destroy]

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

private

def set_product_items
    @product_item = ProductItem.find(params[:id])
end

def product_item_params
    params.require(:product_item).permit(:product_id)
end

end

这里是 ProductsController.rb

class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]


  def show

  end

private

def set_product
  @product = Product.find(params[:id])
end

def product_params
  params.require(:product).permit(:name, :description, :price_usd, :price_isl, :image, :category_id)
end

结束

这是routes.rb文件

Rails.application.routes.draw do

 resources :categories
 resources :labels
 resources :products

 resources :carts
 resources :product_items

 devise_for :admin_users, ActiveAdmin::Devise.config
  ActiveAdmin.routes(self)
  root 'pages#index'

只有实例变量可用于视图。

def create
    @product      = Product.find(params[:product_id]) # Prefix variable name with @
    @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

你的观点:

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

您应该能够将对象传递给 _path 助手。