2014-03-06 27 views
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 ?

回答

3

問題has_many答案。由於您已經設置了has_many關係,因此rails會在Question模型中爲您創建一個動態方法,如answers。在問題實例上調用answers方法後,您將獲得該特定問題的所有答案。

對於如:

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將導致查詢如下:

SELECT "answers".* FROM "answers" WHERE "answers"."question_id" = ? [["question_id", 10]] 

在你的情況,你可以修改如下視圖代碼:

<% @questions.each do |q| %> 
    <%= q.question %> 
    <% q.answers.each do |a| %> 
     <%= a.answer %> 
    <% end %> 
    <br> 
    <br> 
<% end %> 
+0

謝謝,這真的很有幫助。像這樣的例子應該放在rails文檔中......這裏沒有什麼明確的。 – user797963

+1

+1,完美答案:) – SagarPPanchal