Created
April 21, 2011 22:46
-
-
Save slayer/935641 to your computer and use it in GitHub Desktop.
SQL JOIN via AREL in Rails 3
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
# Simple JOIN | |
User.joins(:account) # User -> Account | |
# Will produce | |
# SELECT `users`.* FROM `users` INNER JOIN `accounts` ON `accounts`.`user_id` = `users`.`id` | |
# Complicated JOIN | |
Trait.joins(:user => :account) # Trait -> User -> Account | |
# Will produce | |
# SELECT `traits`.* FROM `traits` INNER JOIN `users` ON `users`.`id` = `traits`.`user_id` INNER JOIN `accounts` ON `accounts`.`user_id` = `users`.`id` | |
# And more complicated JOIN | |
Completion.joins(:trait => {:user => :account}) # Completion -> Trait -> User -> Account | |
# Will produce | |
# SELECT `completions`.* FROM `completions` INNER JOIN `traits` ON `traits`.`id` = `completions`.`trait_id` INNER JOIN `users` ON `users`.`id` = `traits`.`user_id` INNER JOIN `accounts` ON `accounts`.`user_id` = `users`.`id` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does not matter if it solves the problem, don't get too focused on tech.