I have a 'landing.html.erb' under a folder 'Welcome' in my Views. In the WelcomeController, I have the following:
def landing
@quiz = Quiz.new
end
to create a new Quiz. When the User clicks the create button,
def create
@quiz = current_user.quiz.build(quiz_params)
if @quiz.save
flash[:success] = "Updated"
redirect_to @quiz
else
render 'new'
end
end
def quiz_params
params.require(:quiz).permit(:q1)
end
is the code I have for the QuizzesController. However, this gives the error:
undefined method `build' for nil:NilClass
specifically at the line
@quiz = current_user.quiz.build(quiz_params)
I ran the rails console and typed Quiz.new and it displayed every field as 'nil' and I'm not entirely sure what I need to modify and would appreciate guidance.
The Quiz model belongs_to User. The User has_one Quiz.
Thank you very much.
Here I am assuming you are having has_one association among user and quiz. So for build the associated object you need to use the following code.
current_user.build_quiz(quiz_params)
This will build the quiz object with the user_id field contains the id of the current user and other fields according to quiz_params.