Have you ever needed to get the most recent record for each user in #rails, but didn't know how to do it without using map?

Here's one way to do it with Active Record 👇
Calling group(:user_id).minimum(:id) returns a hash where the key is the user_id and the value is the ID of their latest (or first) post. Calling .values simply returns the IDs.

We can then pass that list to where(id:) to return a list of the latest (or first) posts per user.
Since the IDs are set in sequential order, the minimum ID is the ID of the user's first post, and the maximum ID is the ID of the user's latest post.
This could also be achieved with the created_at column instead of the ID column, since a higher ID doesn't always mean that the record is the latest.

This is especially true is a user is able to control when a post is created or published.
I've received a lot of thoughtful feedback on this!

Although one of the most performant solutions is to use raw SQL in a `select` call, I wanted to see if this could be achieved with Active Record only.

Here's an optimization that prevents a large hash from being returned.

• • •

Missing some Tweet in this thread? You can try to force a refresh
 

Keep Current with Steve Polito

Steve Polito Profile picture

Stay in touch and get notified when new unrolls are available from this author!

Read all threads

This Thread may be Removed Anytime!

PDF

Twitter may remove this content at anytime! Save it as PDF for later use!

Try unrolling a thread yourself!

how to unroll video
  1. Follow @ThreadReaderApp to mention us!

  2. From a Twitter thread mention us with a keyword "unroll"
@threadreaderapp unroll

Practice here first or read more on our help page!

Did Thread Reader help you today?

Support us! We are indie developers!


This site is made by just two indie developers on a laptop doing marketing, support and development! Read more about the story.

Become a Premium Member ($3/month or $30/year) and get exclusive features!

Become Premium

Don't want to be a Premium member but still want to support us?

Make a small donation by buying us coffee ($5) or help with server cost ($10)

Donate via Paypal

Or Donate anonymously using crypto!

Ethereum

0xfe58350B80634f60Fa6Dc149a72b4DFbc17D341E copy

Bitcoin

3ATGMxNzCUFzxpMCHL5sWSt4DVtS8UqXpi copy

Thank you for your support!

Follow Us on Twitter!

:(