Maximus S
Maximus S

Reputation: 11125

Rails query] difference between joins and includes

@teachers = User.joins(:students).where("student_id IS NOT NULL")

The above works, the below doesn't.

@teachers = User.includes(:students).where("student_id IS NOT NULL")

As far as I understand, joins and includes should both bring the same result with different performance. According to this, you use includes to load associated records of the objects called by Model, where joins to simply add two tables together. Using includes can also prevent the N+1 queries.

First question: why does my second line of code not work?

Second question: should anyone always use includes in a case similar to above?

Upvotes: 1

Views: 1931

Answers (1)

cpuguy83
cpuguy83

Reputation: 5993

You use joins when you want to query against the joined model. This is doing an inner join between your tables.

Includes is when you want to eager load the associated model to the end result.
This allows you to call the association on any of the results without having to again do the db lookup. You cannot query against a model that is loaded via includes. If you want to query against it you must use joins( you can do both! )

Upvotes: 1

Related Questions