[英]Rails query through association limited to unique associated objects?
class User
has_many :books
I need a query that returns: 我需要一个返回的查询:
Three most recent books belonging to unique users. 属于唯一用户的三本最新书籍。 Ie if my DB has
即如果我的数据库有
users:
id: 1, name: "John"
id: 2, name: "Mary"
id: 3, name: "Bob"
books:
id: 1, title: "Ender's Game", user_id: 1
id: 2, title: "Dune", user_id: 1
id: 3, title: "The Martian", user_id: 1
id: 4, title: "The Shining", user_id: 2
id: 5, title: "The Call of Cthulhu", user_id: 2
id: 6, title: "The Hobbit", user_id: 3
I expect the query to return books with id: [3, 5, 6] as those are the last books of each respective user. 我希望查询返回ID为[3、5、6]的图书,因为它们是每个用户的最后一本书。
So far I have 到目前为止,我有
Book.joins(:user).where( ... ).order(created_at: :desc).first(3)
The placeholder .where
is where the actual hard part would happen. 占位符
.where
是发生实际困难部分的位置。
I am aware I could return the needed objects using a ruby loop, but perhaps there is a scope-friendly solution? 我知道我可以使用ruby循环返回所需的对象,但是也许有一个范围友好的解决方案?
您可以使用子查询:
books = Book.where(id: Book.select('MAX(id) AS id').group(:user_id)).order(created_at: :desc)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.