What's the difference between "includes" and "joins" in ActiveRecord query?

stores = Store.joins(:car)

This will return all stores for which there is a car. stores[0].car will result in another query.

stores = Store.includes(:car)

This will return all stores, car or no car. stores[0].car will not result in another query.

stores = Store.includes(:car).joins(:car)

This will return all stores with a car. stores[0].car will not result in another query. I wouldn't recommend this for has_many relationships, but it works great for has_one.


:joins joins tables together in sql, :includes eager loads associations to avoid the n+1 problem (where one query is executed to retrieve the record and then one per association which is loaded).

I suggest you read their sections in Rails Guides to get more info.


:joins returns read-only objects, :includes does not

:joins uses inner join, :includes uses outer join.

the main reason of :includes is eager loading, to avoid the N+1 problem of loading in attributes of each object using a separate query.