Last active
February 19, 2019 04:41
-
-
Save jenny-codes/26d2e5ffa61798ad3ef92b5916a577e0 to your computer and use it in GitHub Desktop.
Examples of when to use :joins provided by Rails' ActiveRecord
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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