[英]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.
我要呈现每个父级的最后一个孩子,按孩子的created_at日期排序。 I'm having trouble figuring out how to do this with active record & rails.
我在弄清楚如何使用活动记录和轨道进行此操作时遇到了麻烦。
Try: 尝试:
youngest_kids = Parent.includes( :children ).map { |parent| parent.children.last }.compact
compact
removes the nil
s returned for parent
s without children
compact
删除没有children
parent
返回的nil
try 尝试
Parents.all.each do |parent|
parent.children.order(:created_at).last
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.