首页 > 解决方案 > 找不到身份证

问题描述

在此处输入图像描述我在我的控制器中收到此错误。它找不到产品ID。不确定为什么会出错。

class ProductsController < ApplicationController
  before_action :set_product, only: [:index, :new, :create]
   before_action :authenticate_user!, except: [:show]

  def index
     @products = current_user.products
  end

  def show
  end

  def new
    @product = current_user.products.build
  end

  def edit
  end

  def create
    @product = current_user.products.build(product_params)

      if @product.save
        redirect_to listing_products_path(@product), notice: "Saved..."
      else
        flash[:alert] = "Something went wrong..."
        render :new
      end
  end

  def update
      if @product.update(product_params)
        flash[:notice] = "Saved..."
      else
        flash[:notice] = "Something went wrong..."
      end
      redirect_back(fallback_location: request.referer)
  end

  def destroy
    @product.destroy
    respond_to do |format|
      format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' }
      format.json { head :no_content }
    end
  end



  private

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

    def product_params
      params.require(:product).permit(:description, :features, :listing, :location, :photo_upload, :pricing)
    end
end

我必须为用户签名才能创建产品。在我的模型中,我有一个 products belongs_to user 和 User has_many products

标签: ruby-on-railsruby

解决方案


您正在尝试在index操作之前使用参数中的 id 加载产品。但index路线通常不提供任何params[:id].

要修复此错误,只需更改

before_action :set_product, only: [:index, :new, :create]

before_action :set_product, only: [:show, :edit, :update]

推荐阅读