Ruby on Rails ActiveRecord Query Interface Joins


Example

joins() allows you to join tables to your current model. For ex.

User.joins(:posts)

will produce the following SQL query:

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

Having table joined, you will have access to it:

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

Pay attention on plural form. If your relation is :has_many, then the joins() argument should be pluralized. Otherwise, use singular.

Nested joins:

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

which will produce:

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