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.
Asked
Active
Viewed 268 times
2 Answers
2
Try:
youngest_kids = Parent.includes( :children ).map { |parent| parent.children.last }.compact
compact
removes the nil
s returned for parent
s without children

roob
- 1,116
- 7
- 11
-
Thanks! Just saw this – Jackson Cunningham Apr 19 '16 at 20:09
0
try
Parents.all.each do |parent|
parent.children.order(:created_at).last
end

doubler
- 121
- 7
-
Hmmm.. I was trying to think of a way to do it quicker, with a single DB query – Jackson Cunningham Dec 18 '15 at 00:25
-
In that case follow instructions here [link](http://stackoverflow.com/questions/2111384/sql-join-selecting-the-last-records-in-a-one-to-many-relationship) – doubler Dec 18 '15 at 00:34
-