我是新手学习Rails 3并完成Q& A应用教程。我只是想知道为什么我不能这样做(我得到一个错误)将特定答案与问题联系起来。它适用于当前用户......
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
答案 0 :(得分:1)
执行以下操作
@answer = @question.answers.build(params[:answer)
与此相同
@answer = Answer.new(params[:answer])
@answer.question_id = @question.id
执行build
会将关系属性添加到新答案中,在本例中为question_id
至于错误,你能提供你收到的错误类型吗?