Rails - 如何处理多个关联

时间:2015-09-26 18:01:52

标签: ruby-on-rails ruby-on-rails-4 associations

我们说我有一个名为学生的模型,

名为测试的模型(学生在学校参加考试)

一个名为 StudentTest 的关联模型,它说明特定学生何时完成特定考试,在什么情况下等等。

名为问题的模型,将由测试

使用

一个名为 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才能获得它的身份。

我的问题是:我是否可以宣布任何关联,以便能够以下列方式回答答案:

st.student_answers

或类似的东西?

编辑1:我在考虑使用关系

我想的是:

student_test.rb

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

但是,当然,这有语法错误。通过只会接受一个论点

1 个答案:

答案 0 :(得分: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

这允许您从指定的测试中提取所有答案。

相关问题