Includes loads the association data in a separate query in the default
case just like preload.
However it is smarter than preload. Above we saw that preload failed
for query User.preload(:posts).where("posts.desc='ruby is awesome'").
Let’s try same with includes.
User.includes(:posts).where('posts.desc = "ruby is awesome"').to_a# =>SELECT"users"."id"ASt0_r0,"users"."name"ASt0_r1,"posts"."id"ASt1_r0,"posts"."title"ASt1_r1,"posts"."user_id"ASt1_r2,"posts"."desc"ASt1_r3FROM"users"LEFTOUTERJOIN"posts"ON"posts"."user_id"="users"."id"WHERE(posts.desc="ruby is awesome")
As you can see includes switches from using two separate queries to
creating a single LEFT OUTER JOIN to get the data. And it also applies
the supplied condition.
So includes changes from two queries to a single query on some cases.
By default for a simple case it will use two queries. Let’s say that for some reason you want to force a simple includes
case to use a single query instead of two. Use references to achieve that.
In the above case no posts data is selected. Above query can also
produce duplicate result. To see it let’s create some sample data.
Wit the above sample data if we execute User.joins(:posts) then this
is the result we get