【问题标题】:Nested routes undefined variable Rails嵌套路由未定义变量 Rails
【发布时间】:2015-04-21 15:16:32
【问题描述】:

我正在尝试构建嵌套路线,如 here 所述,我正在尝试将我的船图片编辑为 <%= link_to "edit", edit_boat_picture_path(@boat, picture) %>。但是当我尝试它时,它会为 #`

引发错误 undefined local variable or methodpicture'

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

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

【问题讨论】:

    标签: ruby-on-rails controller routes nested edit


    【解决方案1】:

    大概你应该改变

    <%= 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

    【讨论】:

    • 是的,我试过了。但不明白背后的逻辑。
    • 我编辑了我的答案以添加一些解释,它有帮助吗?
    • 您在控制器的操作中定义了@picture,但您试图访问不存在的picture 变量。 @variables 在控制器的操作和视图之间共享,而 variables 只是局部变量,仅存在于本地上下文中(控制器的操作或单个视图或单个块等)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    相关资源
    最近更新 更多