2013-05-06 68 views
1

我是學習Rails 3和通過Q &應用教程的新手。我只是想知道爲什麼我不能在一個問題的特定答案中做到這一點(我得到一個錯誤)。它適用於當前用戶...Ruby on Rails,關聯兩個實例的正確方法是什麼?

class AnswersController < ApplicationController 

before_filter :auth, only: [:create] 

def create 
    @question = Question.find(params[:question_id]) 
    **@answer = Answer.new(params[:answer]) 
    @answer.question = @question 
    @answer.user = current_user** 
    if @answer.save 
     flash[:success] = 'Your answer has been posted!' 
     redirect_to @question 
    else 
     @question = Question.find(params[:question_id]) 
     render 'questions/show' 
    end 
end 
end 

的教程說,這是正確的做法:

class AnswersController < ApplicationController 

before_filter :auth, only: [:create] 

def create 
    @question = Question.find(params[:question_id]) 
    **@answer = @question.answers.build(params[:answer])** 
    @answer.user = current_user 
    if @answer.save 
     flash[:success] = 'Your answer has been posted!' 
     redirect_to @question 
    else 
     @question = Question.find(params[:question_id]) 
     render 'questions/show' 
    end 
end 
end 

回答

1

做以下

@answer = @question.answers.build(params[:answer) 

相同這樣

@answer = Answer.new(params[:answer]) 
@answer.question_id = @question.id 

做一個build將關係屬性添加到新答案,在這種情況下,question_id

至於錯誤,您能否提供您收到的錯誤類型?

+0

K,我設法讓它工作。我不確定哪裏出了問題。謝謝。 – user1411469 2013-05-06 14:19:04

相關問題