クイックアンドダーティ:
次のようなクエリを実装して、必要な AR オブジェクトを取得できます。
select s.* from students s, gpas g
where s.id = gpas.student_id
and gpas.id in (select max(id) from gpas group by student_id)
order by gpas.value
created_at が高いレコードほど id が高いと仮定します。
また
より良い方法:
学生の最後のGPAスコアが頻繁に必要になると思います。:last_gpa_score
Student モデルに新しい列を追加してみませんか?
コールバックを使用して、このフィールドの一貫性と自動入力を維持できます。つまり、次のようになります。
class Gpa < ActiveRecord::Base
belongs_to :student
after_save :update_student_last_score
private
def update_student_last_score
self.student.update_last_gpa_score
end
end
class Student < ActiveRecord::Base
has_many :gpas
def update_last_gpa_score
self.last_gpa_score = self.gpas.order("created_at DESC").first.value
end
end
その後、学生の last_gpa_score フィールドで好きなことを行うことができます。