Jackson Cunningham
Jackson Cunningham

Reputation: 5073

Rails active record query: rendering only the most recent child object (ordered by child created_at date) in has_many relationship

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.

Upvotes: 1

Views: 348

Answers (2)

roob
roob

Reputation: 1136

Try:

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

compact removes the nils returned for parents without children

Upvotes: 2

doubler
doubler

Reputation: 121

try

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

Upvotes: 0

Related Questions