Skip to content

Instantly share code, notes, and snippets.

@slayer
Created April 21, 2011 22:46
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • 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`
@revskill10
Copy link

This is not Arel, it's Active Record model

@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