简体   繁体   English

Rails和Active Record:创建一个范围以获取最新的孩子

[英]Rails & Active Record: Create a scope to get the most recent child

A User has_many Books. 用户has_many书。 I want to add a scope to Books that only returns the most recent (created_at) book for each user_id. 我想为“书”添加一个范围,该范围仅返回每个user_id的最新(created_at)书。 Something that groups the books by user_id and only gets the most recent for each user_id ? 是否可以将书籍按user_id分组,并且仅获取每个user_id的最新书籍?

To clarify, I could technically do this: 为了澄清,我可以从技术上做到这一点:

User.all.each { |user| user.books.first }

But I'd like to do it with a clean Active Record query.I'm having a lot of trouble figuring it out, but I imagine the solution isn't too complicated. 但是我想用一个干净的Active Record查询来解决这个问题,但是我很难解决这个问题,但是我认为解决方案并不太复杂。

The easiest way to do this is to create a scope on books that, using a subquery, only selects books that are the latest ones owned by their user: 最简单的方法是在书籍上创建范围,该书籍使用子查询仅选择其用户拥有的最新书籍:

class Book < ActiveRecord::Base
  belongs_to :user

  scope :most_recent, -> {
    where('NOT EXISTS(SELECT 1 FROM books b2 WHERE b2.user_id = books.user_id AND b2.created_at > books.created_at)')
  }
end

This is just one of many options, but it's likely the most re-usable as you can join this relation onto others without worrying about your aggregations conflicting. 这只是众多选择中的一种,但它可能是最可重用的,因为您可以将此关系加入其他对象,而不必担心聚合冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM