1

我是学习 Rails 3 和学习问答应用教程的新手。我只是想知道为什么在将特定答案与问题联系起来时我不能这样做(我得到一个错误)。它适用于当前用户...

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
4

1 回答 1

1

执行以下操作

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

和这样做是一样的

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

在这种情况下,将关系属性build添加到新答案中question_id

至于错误,您能否提供您收到的错误类型?

于 2013-05-06T14:10:20.230 回答