ruby-on-rails - 找不到身份证
问题描述
我在我的控制器中收到此错误。它找不到产品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
解决方案
您正在尝试在index
操作之前使用参数中的 id 加载产品。但index
路线通常不提供任何params[:id]
.
要修复此错误,只需更改
before_action :set_product, only: [:index, :new, :create]
至
before_action :set_product, only: [:show, :edit, :update]
推荐阅读
- python - SUMPRODUCT 两列 PYTHON
- .net - 使用代码中的 EF(Core) 迁移重置数据库/表
- routes - 如何在openshift中将证书更改为oc命令?
- go - go: bun: bun ORM 中不区分大小写的字段名
- asp.net-mvc - 如何在控制器方法中反序列化对象时设置 DateTime UTC?
- azure-logic-apps - Azure 逻辑应用程序中大小为 20+MB 的大块逗号分隔平面文件并转换为 Json - ActionResultsSizeLimitExceeded
- azure-devops - 了解作业请求返回的信息
- python - 是否可以从 jupyterlab 启动器中隐藏内核?
- github - 如何设置 GitHub 操作以评论新 PR?
- python-3.x - 我无法从生产中的 url 中删除端口 8000