Skip to content

Instantly share code, notes, and snippets.

@jenny-codes
Last active February 19, 2019 04:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jenny-codes/26d2e5ffa61798ad3ef92b5916a577e0 to your computer and use it in GitHub Desktop.
Save jenny-codes/26d2e5ffa61798ad3ef92b5916a577e0 to your computer and use it in GitHub Desktop.
Examples of when to use :joins provided by Rails' ActiveRecord
# Speaker -> Talks
# CORRECT USAGE
# Select speakers that have one or more talks and returns all attributes (columns) plus talk's title.
Speaker.joins(:talks).select('distinct speakers.*, talks.title as talks_title').to_a
# SELECT distinct speakers.*, talks.title as talks_title FROM `speakers` INNER JOIN `talks` ON `talks`.`speaker_id` = `speakers`.`id`
# Select speaker whose associated talk(s) is at status 5.
Speaker.joins(:talks).where(talks: {status: 5})
# SELECT `speakers`.* FROM `speakers` INNER JOIN `talks` ON `talks`.`speaker_id` = `speakers`.`id` WHERE `talks`.`status` = 5
# INCORRECT USAGE:
# This produces N+1 queries.
Speaker.joins(:talks).where(talks: {status: 5}).map{ |speaker| speaker.talks.count }
# SELECT `speakers`.* FROM `speakers` INNER JOIN `talks` ON `talks`.`speaker_id` = `speakers`.`id` WHERE `talks`.`status` = 5
# SELECT COUNT(*) FROM `talks` WHERE `talks`.`speaker_id` = 907
# SELECT COUNT(*) FROM `talks` WHERE `talks`.`speaker_id` = 904
# SELECT COUNT(*) FROM `talks` WHERE `talks`.`speaker_id` = 903
# ...(1000+ rows omitted)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment