Reputation: 3027
I'm building a simple rails application as a learning project, and am having trouble figuring out how to actually use the results from a one to many query. As far as I can tell, the query itself is fine, but I can't seem to use the results.
Here's my db schema:
create_table "tests", force: true do |t|
t.string "name"
t.integer "subject_id"
t.string "description"
end
create_table "questions", force: true do |t|
t.text "question"
t.integer "test_id"
end
create_table "answers", force: true do |t|
t.integer "question_id"
t.text "answer"
end
Here are my models:
class Test < ActiveRecord::Base
has_many :questions
belongs_to :subject
end
class Question < ActiveRecord::Base
has_many :answers
belongs_to :test
end
class Answer < ActiveRecord::Base
belongs_to :questions
end
Now, in the controller I'm using, I'm setting an instance variable with this Active Record query (hardcoded the test_id for now):
@questionSet = Question.includes(:answers).where("test_id = ?", 1)
I can then go and get all of the questions out of the view, but how do I get the answers as well? It's like I need a nested for loop - one to loop through the questions, then another to get all answers where question_id matches the id in the question object. These active record objects are a bear to work with.
Here's what I have, which will output the questions, but I cannot get the answers to output:
<% @questions.each do |q| %>
<%= q.question %>
<!--need to loop through answers and output answers for this question (where quesiton_id)-->
<br>
<br>
<% end %>
How do I loop through my answer active record objects and output them if question_id = q.id?
Upvotes: 1
Views: 885
Reputation: 53038
A Question has_many
Answers. As you have set has_many
relationship, rails will create a dynamic method for you in Question model as answers
. Upon calling answers
method on an instance of Question, you will get all the answers for that particular question.
For eg:
q = Question.find(10) ## Returns Question record with id 10 from questions table
q.answers ## Returns all the answers mapped to question with id 10
q.answers
will result in a query as below:
SELECT "answers".* FROM "answers" WHERE "answers"."question_id" = ? [["question_id", 10]]
In your case, you can modify the view code as below:
<% @questions.each do |q| %>
<%= q.question %>
<% q.answers.each do |a| %>
<%= a.answer %>
<% end %>
<br>
<br>
<% end %>
Upvotes: 4