Rails :include vs. :joins
It appears that the :include
functionality was changed with Rails 2.1. Rails used to do the join in all cases, but for performance reasons it was changed to use multiple queries in some circumstances. This blog post by Fabio Akita has some good information on the change (see the section entitled "Optimized Eager Loading").
.joins
will just joins the tables and brings selected fields in return. if you call associations on joins query result, it will fire database queries again
:includes
will eager load the included associations and add them in memory. :includes
loads all the included tables attributes. If you call associations on include query result, it will not fire any queries
The difference between joins and include is that using the include statement generates a much larger SQL query loading into memory all the attributes from the other table(s).
For example, if you have a table full of comments and you use a :joins => users to pull in all the user information for sorting purposes, etc it will work fine and take less time than :include, but say you want to display the comment along with the users name, email, etc. To get the information using :joins, it will have to make separate SQL queries for each user it fetches, whereas if you used :include this information is ready for use.
Great example:
http://railscasts.com/episodes/181-include-vs-joins