Joins
suggest changejoins 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"
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents