我正在尝试创建一个方法,但是出现错误:
undefined local variable or method 'product_params'
我不明白问题是什么。
class ProductsController < ApplicationController
before_action :set_product, only: %i[show]
def new
@product = Product.new
end
def create
@product = Product.new(product_params)
respond_to do |format|
if @product.save
format.html { redirect_to @product, notice: 'Product was successfully created.' }
format.json { render :show, status: :created, location: @product }
else
format.html { render :new }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
private
def set_product
@product = Product.find(params[:id])
end
def product_params
params.require(:product).permit(:title, :description)
end
end
end
我的参数是:
Parameters: {"authenticity_token"=>"eupRBo6LO4xQbJfBSDJOC6SOesNJ0GMeBMZRHijgvXvx4pn6Lw2jeIVCQ+XjqaDl8g6Dck1WsOYMiSMa8s4UMQ==", "product"=>{"title"=>"test_title", "description"=>"test_description"}, "commit"=>"Submit"}
答案 0 :(得分:3)
问题是respond_to
块的结尾缩进到create
函数的结尾,而实际上所有私有函数都在create函数之内。更改代码,使其看起来像这样:
class ProductsController < ApplicationController
before_action :set_product, only: %i[show]
def new
@product = Product.new
end
def create
@product = Product.new(product_params)
respond_to do |format|
if @product.save
format.html { redirect_to @product, notice: 'Product was successfully created.' }
format.json { render :show, status: :created, location: @product }
else
format.html { render :new }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
private
def set_product
@product = Product.find(params[:id])
end
def product_params
params.require(:product).permit(:title, :description)
end
end