找不到ID

时间:2019-01-10 20:53:13

标签: ruby-on-rails ruby

enter image description here我的控制器出现此错误。它找不到产品编号。不知道为什么会出错。

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

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

2 个答案:

答案 0 :(得分:0)

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

要解决此错误,只需更改

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

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

答案 1 :(得分:0)

Id无需执行索引操作,因为此“所有记录”的显示列表已更改

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

收件人

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