如果你想要所有学生,那么这在活动记录中有点不重要。
识别最后一个学生记录听起来很重要,可以从范围中受益:
def self.latest_for_student
where("not exists (select null from student_records sr2 where sr2.student_id = student_records.student_id and sr2.start_date > student_records.start_date)")
end
...这意味着“返回相同student_id的student_records中不存在另一行的行,以及更大的start_date”
或者……
def self.latest_for_student
where("student_records.start_date = (select max(start_date) from student_records sr2 where sr2.student_id = student_records.student_id)")
end
... 这意味着“返回开始日期等于该学生 ID 的最大开始日期的行”
那么你可以:
class Student
has_one :last_student_record, -> {merge(StudentRecord.latest_for_student)}, :class_name => "StudentRecord"
has_one :last_class_course, :through => :last_student_record, :source => :class_course
end
class ClassCourse
has_many :last_records_for_student, -> {merge(StudentRecord.latest_for_student)}, :class_name => "StudentRecord"
has_many :students_having_as_last_course, :through => : last_records_for_student, :source => :student
end
那么你应该能够:
@course.students_having_as_last_course
有点复杂...可能是语法错误...如果有请告诉我。