部分中未定义的局部变量

时间:2013-09-01 02:10:36

标签: ruby-on-rails

我是rails的新手,遇到了一些麻烦。我正在接受

undefined local variable or method `answer'
<_>我的_answer.html.erb部分错误

这是我的answers_controller.rb:

  class AnswersController < ApplicationController
  before_action :set_answer, only: [:show, :edit, :update, :destroy]


 def index
   @question = Question.find params[:question_id]
   @question.answers
 end


  def show
  end


 def new
    @question = Question.find params[:question_id]
 end


 def edit
 end


  def create
   @question = Question.find(params[:question_id])
   @answer = @question.answers.create(answer_params)

   respond_to do |format|
    if @answer.save
     format.html { redirect_to @comment, notice: 'Answer was successfully created.' }
     format.json { render action: 'show', status: :created, location: @answer }
   else
    format.html { render action: 'new' }
    format.json { render json: @answer.errors, status: :unprocessable_entity }
   end
  end
 end


   def update
     respond_to do |format|
      if @answer.update(answer_params)
      format.html { redirect_to @answer, notice: 'Answer was successfully updated.' }
    format.json { head :no_content }
   else
      format.html { render action: 'edit' }
      format.json { render json: @answer.errors, status: :unprocessable_entity }
     end
   end
 end


  def destroy
    @answer.destroy
    respond_to do |format|
     format.html { redirect_to answers_url }
     format.json { head :no_content }
   end
 end

和我的_answer.html.erb文件:

  <%=div_for(answer) do %>
  <div class="questioncontainer">
   <p> 
  <%= answer.body %>
   </p>
   </div>
   <% end %>

如果重要,我的资源:答案嵌套在资源中:问题。

我感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

尝试使用div_for(@answer)代替answer。当您在控制器和视图之间进行通信时,始终使用@variables进行通信。也许你应该花点时间阅读一下:http://guides.rubyonrails.org/layouts_and_rendering.html