Rails活动记录查询:只呈现has_many关系中最近的子对象(按childcreated_at date排序)



父对象有_个:子对象。我想呈现每个Parent的最后一个子项,按子项的created_at日期排序。我很难弄清楚如何使用活动唱片&轨道。

尝试:

youngest_kids = Parent.includes( :children ).map { |parent| parent.children.last }.compact

compact删除为没有childrenparent返回的nil

尝试

Parents.all.each do |parent|
  parent.children.order(:created_at).last
end

最新更新