简体   繁体   English

Rails活动记录查询:仅呈现has_many关系中最近的子对象(按子created_at日期排序)

[英]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.

相关问题 Rails:has_many活动记录查询 - Rails: has_many Active record query ActiveRecord PSQL按最近的has_many association + pagination的created_at排序 - ActiveRecord PSQL sort by most recent created_at of has_many association + pagination Rails和Active Record:创建一个范围以获取最新的孩子 - Rails & Active Record: Create a scope to get the most recent child Rails 4:使用具有has_many通过关系的嵌套形式保存子记录ID,但不保存其属性 - Rails 4: child record ID is saved but not its attributes, using nested form with has_many through relationship Active Record查询通过关系查找与Rails has_many中的所有条件匹配的记录 - Active Record query to find records that match all conditions in Rails has_many through relationship 基于has_many关系的属性的Active Record查询? - Active Record query based on property of has_many relationship? Rails活动记录has_many自定义查询 - rails active record has_many custom query Rails:Active Record has_many关系始终从初始查询中仅获取经过过滤的结果 - Rails: Active Record has_many relation to always fetch only filtered results from initial query Rails Active Record,从has_many:through关系中获取相关记录,并且where子句通过 - Rails Active Record, get related record from has_many :through relationship with where clause on through record 获取具有has_many关系的孩子的父母? - Get the parent of a child in a has_many relationship?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM