1

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

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

6 Comments

Hi, thanks a lot for the suggestion but '@survey.question.build' does not seem to work when there is a 'has_one' relationship between the models. I have to use the following format '@survey.build_question' otherwise i get the following error message 'undefined method `build' for nil:NilClass'
If i am to use --- @survey = Survey.new @question = @survey.build_question @answer = @question.answer.build, then how do i tackle the @answer part ?? :(
I mean '@answer = @question.answer.build' is now giving me the following error message 'undefined method `build' for nil:NilClass'
I got it --it should be '@answer = @question.build_answer'
Question and Answer are in a has_one/belongs_to relationship and i guess that's the reason i was getting an error for the 3rd line of code but using '@answer = @question.build_answer' seems to be doing the job :). Thanks a lot for your help
|
1
@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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.