Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Examples of when to use :joins provided by Rails' ActiveRecord
# Speaker -> Talks
# 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
# 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