嵌套路由未定义变量 Rails

Nested routes undefined variable Rails

我正在尝试构建嵌套路线,并且如上所述 here 我正在尝试将我的船图片编辑为 <%= link_to "edit", edit_boat_picture_path(@boat, picture) %>。但是当我尝试它时,它会抛出错误 undefined local variable or methodpicture' for #<#:0x007f9637811ee0>`

我的图片控制器是; (可能销毁也是错误的)

class PicturesController < ApplicationController
  before_action :logged_in_user
  before_filter :load_parent

  def index
    @picture = @boat.pictures.all
  end

  def new
    @picture = @boat.pictures.new
  end

  def show
    @pictures = @boat.pictures.find(params[:id])
  end


  def create

    @picture = @boat.pictures.new(picture_params)
    if @picture.save
      #flash[:success] = "Continue from here"
      render 'show'
    else
      render 'new' 
    end
  end

  def edit
    @picture = Picture.find(params[:id])
  end

  def update
    @picture = @boat.pictures.find(params[:id])

    if @picture.update_attributes(picture_params)
      flash[:notice] = "Successfully updated picture."
      render 'show'
    else
      render 'edit'
    end
  end

  def destroy

    @picture = @boat.pictures.find(params[:id])
    @picture.destroy
    flash[:notice] = "Successfully destroyed picture."
    redirect_to @picture.boat
  end


  private

    def picture_params
      params.require(:picture).permit(:name, :image)
    end

    def load_parent
     @boat = Boat.find(params[:boat_id])
    end

end

想必你应该改变

<%= link_to "edit", edit_boat_picture_path(@boat, picture) %>

<%= link_to "edit", edit_boat_picture_path(@boat, @picture) %>

那里的钥匙正在将 picture 更改为 @picture。这样做的原因是您在控制器中声明 @picture(实例变量),而不是 picture(局部变量)。在控制器的方法中声明和定义实例变量时,它也可以在相应的视图中访问。但是,当在控制器的方法中声明局部变量时,它在您的视图中不可用。

因此,即使您 在您的控制器方法中声明了 picture 而不是 @picture,它也不会在您的视图中访问,因为它是局部变量。

有关 ruby 变量的五种类型的详细信息,请参阅 this link