【问题标题】:Rails - How to deal with multiple associationRails - 如何处理多重关联
【发布时间】:2015-09-26 18:01:52
【问题描述】:

假设我有一个模型,名为 Student

一个名为Test的模型(学生在学校参加的测试)

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

一个名为 Questions 的模型,将被测试使用

一个名为 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

但是为了得到它的 id 而重复变量 st 似乎太多余了。

我的问题是:是否有任何关联我可以声明以使检索答案成为可能:

st.student_answers

还是类似的?

编辑 1:我对关系使用的看法

我在想这样的事情:

student_test.rb

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

当然,这有语法错误。 through 只会接受一个参数

【问题讨论】:

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


    【解决方案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
    

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

    【讨论】:

    • 您正确理解了我的问题。这是图表。但是,请看我的编辑。你认为我只能通过声明关系来实现这一点,比如有很多通过吗?
    • 我查看了编辑。这也是我的第一个想法,但你看,如果我做 st.student_answers,它会给出只匹配 question_test_id 的记录,这意味着,我会得到这些问题的答案,但不一定来自特定的学生
    • 问题是它应该与“st” questions_test 和“st” student 都有关......我想使用“has many through”,但“through”只需要一个参数。你仍然认为有办法只用关系来做到这一点吗?
    • 是的,进行另一次编辑。越来越清晰了
    • ArgumentError:未知键::条件。有效键是::class_name, :class, :foreign_key, :validate, :autosave, :table_name, :before_add, :after_add, :before_remove, :after_remove, :extend, :primary_key, :dependent, :as, :through, : source, :source_type, :inverse_of, :counter_cache, :join_table, :foreign_type
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多