2013-09-01 172 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