How to get the latest record from each group in ActiveRecord?

后端 未结 5 1997
暖寄归人
暖寄归人 2020-12-14 01:07

In my Ruby on Rails application I have a database structure like this:

Project.create(:group => \"1\", :date => \"2014-01-01\")
Project.create(:group =         


        
5条回答
  •  星月不相逢
    2020-12-14 01:31

    I spent some time battling this and thought I'd share what I found to be the cleanest and stunningly easy solution (assuming date or other sorting field contains unique values):

    Project.group(:group).maximum(:date)
    

    Hat tip to qarol for posting this in this comment.

提交回复
热议问题