Reputation: 2176
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
Upvotes: 1
Views: 2563
Reputation: 43153
@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.
Upvotes: 1
Reputation: 12165
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
Upvotes: 2