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

后端 未结 5 1998
暖寄归人
暖寄归人 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:35

    Something like this?

    Project.select(:group).map(&:group).uniq.each do |grp|
      puts Project.where(group: grp).order("date DESC").last
    end
    

    This will go through all your groups and identify the unique ones. In your example it should return ["1", "2"]. Then it iterates over that array and selects the last Project with a group id of 1 and the last Project with a group id of 2.

    ** Update **

    Just realized you said "latest" and not "last" which required adding an order to ensure latest works. Last still pulls just one.

提交回复
热议问题