2013-09-01 63 views
1

我是新来的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 %> 

如果它的事项,我的资源:答案嵌套在资源:问题。

我感谢任何帮助!

+0

你在哪里/如何提供答案? –

+0

哪个动作给出错误?什么:set_answer做什么? – Fred

+0

@DaveNewton我在_question.html.erb文件中使用<%= render“回答它/ answers”%> – user2736480

回答

0

尝试使用div_for(@answer)而不是answer。当你在控制器和视图之间进行通信时,你总是用@variables这样做。也许你应该花点时间阅读:http://guides.rubyonrails.org/layouts_and_rendering.html

+0

太棒了,这个工程除了现在,当我尝试并输入答案def创建的第二行在answers_controller给我一个未定义的方法'答案'错误。 – user2736480

+0

发生这种情况是因为您错误地创建了答案为'question.answers.create(answer_params)'。我想你应该通过'Answer.create(params [:user_id],params [:answer_body])'或类似的方式来做到这一点,但是我实际上并不知道你的答案的模型。但坦率地说,你真的有一些关于RoR的重要概念。我建议你在开始创建一个RoR应用程序之前,真正挖掘一些书籍或课程。你应该尝试:[Rails for Zombies](http://railsforzombies.org/),它是为初学者设计的,应该会帮助你很多。 –

+0

非常感谢!我肯定会尝试僵尸的Rails。 – user2736480