Skip to content

Instantly share code, notes, and snippets.

@stevepolitodesign
Last active October 5, 2021 20:38
Show Gist options
  • Save stevepolitodesign/1df3bdd1179ef66044bf5e304d73a776 to your computer and use it in GitHub Desktop.
Save stevepolitodesign/1df3bdd1179ef66044bf5e304d73a776 to your computer and use it in GitHub Desktop.
Combine joins and where for better queries

Problem

Query for all courses bookmarked by the current user.

Before

This works, but it requires two queries.

@bookmarks = current_user.bookmarks
@courses = Course.where(id: @bookmarks.select(:bookmarkable_id))

After

This is more efficient because it results in one query thanks to the call to joins.

@courses = Course.joins(:bookmarks).where("bookmarks.user_id = ?", current_user.id)

https://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-where-label-Joins

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment