当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails- nested attributes for 'has_one' relationship

问题描述:

I need some help concerning nested attributes in models with 'has_one' relationship.

Model Survey has 1 question

Model Question has 1 answer

How do i build the 'answer' in the code below

def new

@survey = Survey.new

@survey.build_question # build one question

@survey.question.answer.build #this part is not working

end

Please can anybody tell me how to build the answer as the code "@survey.question.answer.build" is not correct.

Many many thanks for your help

网友答案:

You must build the answer on the newly created Question instance since it's not yet been saved.

@survey = Survey.new
@question = @survey.build_question
@answer = @question.build_answer
# ... at some point in the future
@survey.save
网友答案:
@survey = Survey.new
@survey.question = Question.new
@survey.question.answer = Answer.new
@survey.question.answer = (whatever)
@survey.save!

(or just @survey.save if you don't want to see exceptions)

If you want to make it easier to access these as instance variables in your view you can assign any of them to a variable after you've created them, and the association will be maintained:

@question = @survey.question

It's up to you.

分享给朋友:
您可能感兴趣的文章:
随机阅读: