diasks2
diasks2

Reputation: 2142

Ruby on Rails: passing in a variable to an active record query

This question relates to a RoR quiz app. I am looking to display the results of the quiz, showing both the correct answer as well as the user's answer.

Therefore, in my view, I need to loop through each question and show the question answer, as well as the user's answer. However, I am struggling trying to figure out how to correctly query the user's answer.

To query the user_answer, I need the response_set where the user_id = current_user.id and I need to pass in the question_id as it loops through the each loop. However, I'm stuck on how to accomplish this.

What do I need to do to show the user_answer in the view alongside the correct_answer?

I have 3 models:

Response_set
belongs_to :user
has_many :responses

Reponse
belongs_to :response_set
belongs_to :question

Question
has_many :responses

Table fields:

create_table :response_sets do |t|
  t.integer :user_id

create_table :responses do |t|
  t.integer :response_set_id
  t.integer :question_id
  t.integer :user_answer

create_table :questions do |t|
  t.integer :correct_answer

Controller

@questions = Question.all
@user = current_user.id

View (just looping through the questions and not displaying the user's answer)

<% @questions.each do |question| %>
   <%= question.correct_answer %>
<% end %>

Upvotes: 1

Views: 4688

Answers (2)

diasks2
diasks2

Reputation: 2142

My mentor ended up solving this one for me. Here is the solution that he presented:

"I think a better approach here would be get the responses from the response set and loop over that instead of looping over the questions."

Controller:

 @response_set = Response_set.where("user_id = ?", @user).includes({:responses => :question}).last

View:

 <% @response_set.responses.each do |response| %>
   <%= response.question.correct_answer %>
   <%= response.user_answer %>
 <% end %>

Upvotes: 2

Dhiren Gupta
Dhiren Gupta

Reputation: 1

Add user_id in responses table, this way you don't have to query response_set table. After this you can do something like this inside the loop

 question.responses.where(:user_id => current_user.id).first.user_answer

Upvotes: 0

Related Questions