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.
精彩评论