Skip to content

Instantly share code, notes, and snippets.

@slayer
Created April 21, 2011 22:46
Show Gist options
  • Save slayer/935641 to your computer and use it in GitHub Desktop.
Save slayer/935641 to your computer and use it in GitHub Desktop.
SQL JOIN via AREL in Rails 3
# 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`
@codingpains
Copy link

Does not matter if it solves the problem, don't get too focused on tech.

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