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
@survey = Survey.new
@survey.build_question # build one question
@survey.question.answer.build #this part is not working
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!
@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.