Take the 2-minute tour ×

I just started using rails. Loving it so far, but there's a few things I haven't grasped yet.

One of them is the interaction between joins/includes and associations. For every model you define it's relation (has_many, belongs_to, etc) to other models. And that's enough to make them connect to and find each other by primary keys, right?

So what's the point of using joins/includes then? My own guess is to reduce sql queries and only fetch the necessary objects, but I'd like to be clear about this. Is associations to joins like scope is to order/where etc. Kind of a default behavior that is modifiable?

Would really like to have this straightened out.

share|improve this question

1 Answer 1

Railscast #181 By Ryan Bates covers this very well...

Effectively a "join" is used to join two tables efficiently on the database server. However, by default, only the columns from the first table are included in the dataset. You would use a join to test records in the first table against criteria in the second table.

An "include" is similar to a join, but does an efficient data retrieval on the second table's rows for any records that are relevant, and populates the Rails ActiveRecord cache with those records.

So, if you have a User class and a Role class, where a User can have a single Role attached to it, then both the user and role instances will be retrieved from the database at the same time.

User #5 => points to => Role #7

User #10 => points to => Role #12

Retrieving user #5 and #10 from the User table using an includes() will also instantiate roles #7 and #12 using an SQL query such as:

SELECT roles.* FROM roles WHERE id IN (7,12)



share|improve this answer

Your Answer


