Using Select Instead of Pluck in ActiveRecord Queries

A coworker of mine recently gave me a really helpful ActiveRecord tip. A simple example demonstrates it best.

Let's say you want to select users that have made a reported post. This would typically be done with just a join, but there are some cases where you might think to do something like:

User.where(
  id: Post.reported_posts.pluck(:user_id)
)

I always assumed that in cases where I needed to do something like this, I was just stuck using an ActiveRecord relation that would generate two SQL queries like the one above, which is not ideal. However, I recently learned there's a better way!

We can simply do the following instead:

User.where(
	id: Post.select(:user_id).reported_posts)
)

By using select instead, we can write something that looks basically the same, but only generates one SQL query!