Joins

suggest change

joins adds an INNER JOIN to the query. For example:

User.joins(:posts)

produces:

SELECT "users".* FROM "users" INNER JOIN "posts" ON "posts"."user_id" = "users"."id"

After the join, you can filter on the joined table:

User.joins(:posts).where(posts: { title: "Hello world" })

Use the association name. A has_many name is plural. belongs_to and has_one are singular.

Nested joins:

User.joins(posts: :images).where(images: { caption: "First post" })

which produces:

SELECT "users".* FROM "users"
INNER JOIN "posts" ON "posts"."user_id" = "users"."id"
INNER JOIN "images" ON "images"."post_id" = "posts"."id"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents