I am trying to build a simple quiz app, I already have one table for questions and another for answers (answers each have a question_id tag to pull up the multiple choice options for each question).
I have listed out all my multiple choice questions on one page, and I want only the answers that correspond to each question to display below the question, however each MCQ is currently listing the full answer table instead of just the matching answers.
I think it has to do either with my view or controller code that's causing this behaviour (when I change the question ID in my controller to just a single question, the 4 possible answers appear correctly, but when I change it to @questions = Question.all
, then the full answer table returns).
Or it might have to do with using <% @question_answers.each do |question_answers| %>
wrongly.
My pages_controller.rb code:
class PagesController < ApplicationController
def show
end
def home
end
def challenge
@questions = Question.all
@question_answers = QuestionAnswer.where(question_id: @questions.pluck(:id))
# @questions = Question.where(id: 3)
end
end
My view file at pages/challenge.html.erb:
<h1>Challenge</h1>
<% @questions.each do |question| %>
<div class="container">
<p><%= question.question %></p>
<form>
<% @question_answers.each do |question_answers| %>
<input type="radio" name="gender" value=<%= question_answers.answer %>><%= question_answers.answer %><br>
<% end %>
<input type="submit" value="Submit">
</form>
</div>
<% end %>
I want only the answers that correspond to each question to display below the question, any ideas what I'm getting wrong here?
You are wrong with this code:
question_answers
is all records from answer table because you assigned it toQuestionAnswer.where(question_id: @questions.pluck(:id))
You should query only questions that belongs to answer. Assume you have two model and set up association like this:
Then in your view you can get questions belongs to an answer like this:
In controller, you only need:
includes(:question_answers)
is used to avoid N+1 queries when loading answers for each question.