【问题标题】:Rails : NameError in PicsController#updateRails:PicsController 中的 NameError#update
【发布时间】:2017-11-07 20:27:02
【问题描述】:

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

未定义的局部变量或方法 `pic' for # 你的意思是? @pic

提取的源代码(第 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

我该如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-5 ruby-on-rails-5.1


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      • 2021-10-29
      • 2020-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多