Flowdock
joins(*args) public

Performs a joins on args. The given symbol(s) should match the name of the association(s).

User.joins(:posts)
# SELECT "users".*
# FROM "users"
# INNER JOIN "posts" ON "posts"."user_id" = "users"."id"

Multiple joins:

User.joins(:posts, :account)
# SELECT "users".*
# FROM "users"
# INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
# INNER JOIN "accounts" ON "accounts"."id" = "users"."account_id"

Nested joins:

User.joins(posts: [:comments])
# SELECT "users".*
# FROM "users"
# INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
# INNER JOIN "comments" "comments_posts"
#   ON "comments_posts"."post_id" = "posts"."id"

You can use strings in order to customize your joins:

User.joins("LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id")
# SELECT "users".* FROM "users" LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id
Show source
Register or log in to add new notes.
January 19, 2012 - (v3.0.0 - v3.1.0)
0 thanks

Options

I came across the following situation An article has a history of friendly url being that the foreign key that represents the value of the article’s id in the table is called Friend url_id then in that case:

Article.joins(“INNER JOIN friends ON articles.id = friends.url_id”).where(“friends.url like ? ”, url)

if the column url_id was renamed for artigo_id would be easier

Article.joins(:friend).where(“friends.url like ? ”, url)