Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 比较Rails活动记录中的最后一个元素_Sql_Ruby On Rails_Activerecord - Fatal编程技术网

Sql 比较Rails活动记录中的最后一个元素

Sql 比较Rails活动记录中的最后一个元素,sql,ruby-on-rails,activerecord,Sql,Ruby On Rails,Activerecord,我有两个模特,学生和学生。学生记录的属性中有开始日期、结束日期和班级课程id,属于学生 scope = Student.eager_load(:student_record) 现在,我想获取其最新(根据开始日期)学生记录的班级课程id与给定班级课程id相同的学生。类似于: scope = scope.where("student_records.order(start_date asc).last.class_course_id = ?", params[:class_course_id])

我有两个模特,学生和学生。学生记录的属性中有开始日期、结束日期和班级课程id,属于学生

scope = Student.eager_load(:student_record)
现在,我想获取其最新(根据开始日期)学生记录的班级课程id与给定班级课程id相同的学生。类似于:

scope = scope.where("student_records.order(start_date asc).last.class_course_id = ?", params[:class_course_id])
显然,上面的陈述是不正确的,但我希望它描述了我想要得到的东西。

下面应该做些什么

Student.eager_load(:student_record).where("student_records.class_course_id = ?", params[:class_course_id]).order('student_records.start_date asc').last

使用
Order by
子句并下降以获取最新日期
.Order(“student_records.start_date DESC”)
并且在
where
子句中,记录将被过滤掉
。其中(“student_records.class_course_id=?”,参数[:class_course_id])
where
将首先出现,然后
order by desc
将正确排序

scope.where("student_records.class_course_id = ?", params[:class_course_id]).order("student_records.start_date DESC")

您可以执行
.limit(5)
来获取前5条记录,即最新的开始日期。

如果您想要所有学生,那么这在活动记录中有点不重要

识别最后一条学生记录听起来是一件重要的事情,它将从范围中受益:

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
。。。这意味着“返回同一学生id的学生记录中不存在另一行的行,并返回更大的开始日期”

或者

。。。这意味着“返回开始日期等于该学生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

有点复杂。。。可能是语法错误。。。如果有,请告诉我。

仍在试图找出您的解决方案:-)不,这不起作用。我认为它在已经获取匹配项之后才订购。这并没有得到预期的结果。还将获取具有非最后一条记录的匹配项的记录,因此请使用
.limit(1)
范围。其中(“学生记录.班级课程id=?”,参数[:班级课程id])。顺序(“学生记录.开始日期描述”)。限制(1)
@course.students_having_as_last_course