0
我正在構建一個簡單的rails應用程序作爲學習項目,並且無法找出如何實際使用一對多查詢的結果。據我所知,查詢本身很好,但我似乎無法使用結果。導軌 - 使用結果形成一對多的查詢
這裏是我的DB模式:
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
這裏是我的模型:
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
現在,我使用的控制器,我設置這個活動記錄查詢一個實例變量(硬編碼爲test_id現在):
@questionSet = Question.includes(:answers).where("test_id = ?", 1)
然後我就可以去,並得到所有的問題都出在視圖中,但我怎樣才能得到答案?這就像我需要一個嵌套for循環 - 一個循環的問題,然後另一個得到所有的答案,其中question_id匹配問題對象中的id。這些活躍的記錄對象是一個需要解決的問題。
這裏是我有,將輸出的問題,但我不能得到答案輸出:
<% @questions.each do |q| %>
<%= q.question %>
<!--need to loop through answers and output answers for this question (where quesiton_id)-->
<br>
<br>
<% end %>
我如何通過我的回答活動記錄對象,如果它們輸出迴路question_id = q.id ?
謝謝,這真的很有幫助。像這樣的例子應該放在rails文檔中......這裏沒有什麼明確的。 – user797963
+1,完美答案:) – SagarPPanchal