1

A Parent has_many :children. I want to render each Parent's last child, ordered by the child's created_at date. I'm having trouble figuring out how to do this with active record & rails.

Jackson Cunningham
  • 4,973
  • 3
  • 30
  • 80

2 Answers2

2

Try:

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

compact removes the nils returned for parents without children

roob
  • 1,116
  • 7
  • 11
0

try

Parents.all.each do |parent|
  parent.children.order(:created_at).last
end
doubler
  • 121
  • 7