开发者

How to find latest posts - but only one per user?

开发者 https://www.devze.com 2023-02-05 08:27 出处:网络
Let\'s say I have model of posts that belongs to a user. A user has many posts. Is there a fast and simple way to fetch the latest posts created, 开发者_C百科but maximum one per user? So even if user

Let's say I have model of posts that belongs to a user. A user has many posts.

Is there a fast and simple way to fetch the latest posts created, 开发者_C百科but maximum one per user? So even if user A posted the 5 latest post, only the latest is returned, followed by user B's post.

Possible without adding manual logic?


Post.select('DISTINCT posts.*').group(:user_id).order('created_at desc')


The group method will only return one record per group.

Post.group(:user_id)

Update

You can't control which one you get from each group this way but it appears to use the latest one created in the database.

0

精彩评论

暂无评论...
验证码 换一张
取 消