Today I Learned

hashrocket A Hashrocket project

ActiveRecord subselects

So you want to find all the rocketeers who wrote blog posts in a date range.

Blog::Post.where(published_at: 15.years.ago..4.years.ago).includes(:rocketeer).map(&:rocketeer)
  # Blog::Post Load (0.6ms)  SELECT "blog_posts".* FROM "blog_posts"
  #   WHERE ("blog_posts"."published_at" BETWEEN '2000-06-12 14:40:06.429288' AND '2011-06-12 14:40:06.429498')
  # Rocketeer Load (0.7ms)  SELECT "rocketeers".* FROM "rocketeers"
  #   WHERE "rocketeers"."id" IN (12, 13, 14, 16)  ORDER BY "rocketeers"."name"

But you want to do it in one query!

Rocketeer.where(
  id: Blog::Post.where(published_at: 15.years.ago..4.years.ago).select(:rocketeer_id)
)
  # Rocketeer Load (0.9ms)  SELECT "rocketeers".* FROM "rocketeers"
  #   WHERE "rocketeers"."id" IN (
  #     SELECT "blog_posts"."rocketeer_id" FROM "blog_posts"
  #       WHERE ("blog_posts"."published_at" BETWEEN '2000-06-12 14:42:20.005077' AND '2011-06-12 14:42:20.005317'))  ORDER BY "rocketeers"."name"
See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.