DEV Community

Cover image for What is the difference between joins and includes in Rails ActiveRecord?
JetThoughts Dev for JetThoughts

Posted on • Edited on • Originally published at jetthoughts.com

What is the difference between joins and includes in Rails ActiveRecord?

The main difference is that when using includes the eager loading is used. Eager loading allows you to optimize data retrieval by avoiding additional queries to the database.

Let’s see how it works with an example:

Joins:
Image description

We have joined tables, but we don’t get any data from the users table. Therefore, each time the user record is accessed, and there is an additional query to the database.

Includes:
Image description

As you can see, we don’t have any additional queries because we use eager loading and we get the data about the user from memory instead of querying the database.

Top comments (2)

Collapse
 
norybaichorov profile image
Nory Baichorov

Is it better to always use includes?

Collapse
 
jetthoughts-dev profile image
JetThoughts Dev

Includes are useful for presenting data. And Joins can be used to filter data, but you won't need them afterward.