ruby on rails - Where should my Quiz model get 'instantiated'?

I might (still) be thinking about this in the wrong way, but I'm hitting an error that says

"Couldn't find Quiz with 'id'=39"

The line that generates this error is:

if (Quiz.find( 

I think there are 2 problems with this code:

1) The Quiz table has a user_id column that associates it with a User, but I'm (unintentionally) looking for the ID of the quiz.
2) The Quiz never gets instantiated so, even if I looked for the user_id attribute in Quiz, there would be no Quiz to find.

I'd like to know where in my Rails code I should create the Quiz in the first place. Is this something that should happen when a User is created? If so, should the Quiz be instantiated 'in' a @quiz variable in User? And in which method? new? build? initialize? create?

This instantiation, I assume, would need to include setting the new Quiz's user_id to the, so I don't see how that can happen in the model, before current_user is even accessible.

Any clues, much appreciated.

BTW, User has_one :quiz and Quiz belongs_to :user

1 Answer

  1. Oliver- Reply


    You can find your Quiz in several ways:

    • Quiz.where(user_id:
    • current_user.quiz

    If you use Quiz.find(5) (and that is what in the end your Quiz.find(, what you are doing is to search for the Quizz with id = 5

    You can create your Quiz as follows:

    Though the user:

    @quiz = current_user.build_quiz attribute_hash


    @quiz = user_id:, other: :attributes

    and then

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>