Rails : PicsController#update 中的 NameError

Rails : NameError in PicsController#update

我尝试添加更新功能,但遇到以下错误。

undefined local variable or method `pic' for # Did you mean? @pic

Extracted source (around line #30):

     28 end 
     29 def update
     30  if @pic.update(pic.params)
     31   redirect_to @pic, notice: "Updated!!"
     32  else
     33    render 'edit'

我的pics_controller.rb文件如下

class PicsController < ApplicationController
  before_action :find_pic, only: [:show, :edit, :update, :destroy]
  def index
    @pics = Pic.all.order("created_at DESC")
  end
  def show
  end
  def new
    @pic = Pic.new
  end
  def create
    @pic = Pic.new(pic_params)
    if @pic.save
      redirect_to @pic,notice: "Yesss! It was posted!"
    else
      render 'new'
    end
  end
  def edit
  end 
  def update
    if @pic.update(pic.params) 
      redirect_to @pic, notice: "Updated!!"
    else
      render 'edit'
    end
  end
  private
   def pic_params
    params.require(:pic).permit(:title, :description)
  end
  def find_pic
    @pic = Pic.find(params[:id])
  end
end

我该如何解决这个问题?

由于更新方法的范围内没有 pic 变量,因此无法访问它。

我认为您需要的是方法 pic_params 而不是尝试访问名为 pic 和 params 的局部变量,请尝试将代码更新为:

if @pic.update(pic_params) 
  redirect_to @pic, notice: 'Updated!!'
else
  render 'edit'
end