Skip to main content

Rails joins vs includes

joins builds an INNER JOIN so you can filter. It does not load the association. includes loads the association so you can read it without extra queries. They solve different problems, and many pages mix them up.

Tested on Rails 8.1.1 and PostgreSQL 16, . Every example below ran, and the generated SQL is the SQL Rails sent.

The conversion

SQL

SELECT posts.* FROM posts
INNER JOIN users ON users.id = posts.user_id
WHERE users.name = 'u1'

ActiveRecord

Post.joins(:user).where(users: { name: "u1" })

SQL that Rails 8.1.1 generates

SELECT "posts".* FROM "posts" INNER JOIN "users" ON "users"."id" = "posts"."user_id" WHERE "users"."name" = $1

A cleaner alternative

Post.joins(:user).select("posts.*", "users.name AS author_name")

When you only need one column from the other table, joins plus select returns it as an attribute. No second query, no User objects.

Related form

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

What goes wrong

joins does not prevent N+1

Looping Post.joins(:user) and reading post.user.name ran 10 queries for 9 posts. Use includes or preload to load the association.

joins on has-many repeats parents

With 3 users and 9 posts, User.joins(:posts).count returned 9. Add distinct to get 3 users. Use where.associated or EXISTS if you only need a presence check.

joins is INNER

Users without posts disappear from the result. Use left_joins to keep them. See the LEFT JOIN page.

Use both when you filter and read

Filtering on users and reading post.user in a loop needs eager_load or includes with a hash condition. That runs one query with a JOIN and loads the association.

Convert your own joins vs includes query

Paste your SQL and press Convert. Always run .to_sql on the result and compare it with your original.

Questions

What is the difference between joins and includes in Rails?

joins adds an INNER JOIN for filtering and does not load the association. includes loads the association to avoid N+1 and may add a JOIN.

Does joins fix N+1?

No. We measured 10 queries with joins and 2 with includes for the same loop.

Can I use joins and includes together?

Yes. Use joins for the INNER JOIN and includes or preload for loading. Or use eager_load for both in one LEFT JOIN query.