2015-09-26 137 views
1

比方說,我有一個模型,名爲學生Rails的 - 如何處理多個關聯

命名模型測試(測試學生參加在學校)

關聯模型命名爲StudentTest,其中說什麼時候特定的學生做了特定的測試,在什麼情況下等等。

模型名爲問題, l用於測試

關聯模型名爲QuestionTest,它說明哪些問題將在哪些測試上進行。

最後,一個名爲StudentAnswer的模型,其中包含對QuestionTest的引用和對Student的引用。

如果我有

st = StudentTest.first 

我可以這樣做:

st.test.questions_test 

獲得分配給學生的測試題。

不過,如果我想的是學生的答案,我不能做到這一點:

st.test.questions_test.student_answers 

因爲雖然它會得到相關的那些question_test_id的答案,也不會涉及到單靠student_id數據。

另一種方法是

st.test.question_test.student_answers.where(student_id: st.id).all 

st.student.student_answers.where(test_id: st.test_id).all 

但似乎過於冗餘不得不重複可變ST只是爲了得到它的ID。

我的問題是:有,我可以聲明,以使其能夠以檢索答案的任何關聯:

st.student_answers 

或類似的東西?

編輯1:我想利用關係

我喜歡思考的東西什麼:

student_test.rb

has_many :questions_test, through: :test 
has_many :student_answers, through: [:questions_test, :student] 

當然但是,這有語法錯誤。通過將只接受一個參數

回答

1

我如何理解它的基本圖:

Questions    Test    Student 
      \   /  \   /  \ 
      QuestionTest   StudentTest   | 
        |         | 
        \--------------StudentAnswer--------/ 

如果你開始:

st = StudentTest.first 

然後你就可以得到特定學生像這樣的答案:

student_answers = st.student.answers_for(st.test) 

你的answers_for方法看起來像這樣:

# student.rb 
has_many :student_answers 

def answers_for(test) 
    student_answers.where(test: test).all 
end 

這允許您從指定的測試中提取所有答案。

+0

您正確理解我的問題。這是圖。不過,請看看我的編輯。你認爲我只能通過宣告關係才能做到這一點,就像有很多通過關係? – Aleksandrus

+0

是的,這是可能的。我將編輯 –

+0

我查看了編輯。這也是我的第一個念頭,但是你看,如果我做st.student_answers,它會給出只匹配question_test_id的記錄,也就是說,我會爲這些問題得到答案,但不一定是來自具體學生 – Aleksandrus