如何根据3rd table所属的记录进行分组,有很多
How to group the records based to 3rd table belongs to, has many
我有以下代码:
quiz.rb
has_many :quiz_attempts
student.rb
has_many :quiz_attempts
quiz_attempt.rb
belongs_to :student
belongs_to :quiz
我需要做的是从 quiz_attempts table 中获取所有具有测验 ID 的学生记录,并根据它显示测验 table 的记录。
意思是,如果学生参加了 10 次测验 A 和 5 次测验 B,那么我需要将所有这些行显示为来自测验 table 的 2。
鉴于我将只有2条测验记录table,它们与quiz_attempts table.
中的A和B的15条记录共同关联
quiz_attempts 还有 quiz_id
列和 student_id 列,测验 table 中没有学生 ID。
我正在使用的查询是:
@quizzes = @student.quiz_attempts.includes(:quiz)
但问题是,它仍然显示 2 行,但来自 quiz_attempts table,我无法将它们分组为测验 table。
我需要完整的解决方案。
Quiz.joins(quiz_attempts: :student)
.where.not(students: { id: nil })
.group('quizzez.id')
上面所做的基本上是以下内容:
Quiz.joins(quiz_attempts: :student)
- select quizzes
table 中与 quiz_attempts
和 students
table 相关的所有行s.
.where.not(students: { id: nil })
以上 select 只有那些学生已经参加 quiz_attempts
. 的测验
.group('quizzez.id')
说我们不希望多次显示相同的测验,因为很多学生都试图通过它,但只有 uniq 记录。
编辑
如评论中所述,要使上述查询基于 current_user
的 ID,您可以实施 AR scope:
class Quiz < ActiveRecord::Base
scope :by_student_id, lambda { |student_id|
joins(quiz_attempts: :student).where(students: { id: student_id }).group('quizzez.id')
}
end
要使用此范围,您需要编写:
Quiz.by_student_id(current_user.id)
我有以下代码:
quiz.rb
has_many :quiz_attempts
student.rb
has_many :quiz_attempts
quiz_attempt.rb
belongs_to :student
belongs_to :quiz
我需要做的是从 quiz_attempts table 中获取所有具有测验 ID 的学生记录,并根据它显示测验 table 的记录。
意思是,如果学生参加了 10 次测验 A 和 5 次测验 B,那么我需要将所有这些行显示为来自测验 table 的 2。
鉴于我将只有2条测验记录table,它们与quiz_attempts table.
中的A和B的15条记录共同关联quiz_attempts 还有 quiz_id
列和 student_id 列,测验 table 中没有学生 ID。
我正在使用的查询是:
@quizzes = @student.quiz_attempts.includes(:quiz)
但问题是,它仍然显示 2 行,但来自 quiz_attempts table,我无法将它们分组为测验 table。
我需要完整的解决方案。
Quiz.joins(quiz_attempts: :student)
.where.not(students: { id: nil })
.group('quizzez.id')
上面所做的基本上是以下内容:
Quiz.joins(quiz_attempts: :student)
- selectquizzes
table 中与quiz_attempts
和students
table 相关的所有行s..where.not(students: { id: nil })
以上 select 只有那些学生已经参加quiz_attempts
. 的测验
.group('quizzez.id')
说我们不希望多次显示相同的测验,因为很多学生都试图通过它,但只有 uniq 记录。
编辑
如评论中所述,要使上述查询基于 current_user
的 ID,您可以实施 AR scope:
class Quiz < ActiveRecord::Base
scope :by_student_id, lambda { |student_id|
joins(quiz_attempts: :student).where(students: { id: student_id }).group('quizzez.id')
}
end
要使用此范围,您需要编写:
Quiz.by_student_id(current_user.id)