2013-05-06 69 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

相关问题