ruby on rails-'has_one'关系的嵌套属性

时间:2011-01-17 14:48:47

标签: ruby-on-rails

我需要一些有关'has_one'关系的模型中嵌套属性的帮助。

模型调查有一个问题 模型问题有1个答案

如何在下面的代码中构建'答案'

def new
  @survey = Survey.new
   @survey.build_question # build one question
    @survey.question.answer.build #this part is not working

end

任何人都可以告诉我如何建立答案,因为代码“@ survey.question.answer.build”不正确。

非常感谢你的帮助

2 个答案:

答案 0 :(得分:2)

您必须在新创建的Question实例上构建答案,因为它尚未保存。

@survey = Survey.new
@question = @survey.build_question
@answer = @question.build_answer
# ... at some point in the future
@survey.save

答案 1 :(得分:1)

@survey = Survey.new
@survey.question = Question.new
@survey.question.answer = Answer.new
@survey.question.answer = (whatever)
@survey.save!

(如果您不想看到异常,则只需@survey.save

如果您希望更容易在视图中作为实例变量访问这些变量,您可以在创建变量后将其中的任何变量分配给变量,并保持关联:

@question = @survey.question

取决于你。

相关问题