I read that if you use the :include option then it reduces your number
of queries.
Means, whenever it is firing a query to find person same time it eager
loads the company association.
I am confused that what exactly it does? Is it load the company object
in memory? and instead of going to database it takes it from memory.
Can anyone elaborate me what exactly happens when we use the :include
option.
Write some code that uses your find and then accesses person.company
and look in the log to see the queries being used. Repeat without the
:include and you will see the difference.
1) Without :include
My code is :-
def user_details
@user=User.find(params[:id])
@company=@user.company
end
Log Output:-
Processing UsersController#user_details (for 127.0.0.1 at 2010-08-11
10:51:34) [GET]
Parameters: {"id"=>"2"}
User Columns (1.0ms) SHOW FIELDS FROM `users`
User Load (0.4ms) SELECT * FROM `users` WHERE (`users`.`id` = 2)
Company Load (0.4ms) SELECT * FROM `companies` WHERE
(`companies`.user_id = 2) LIMIT 1
Rendering template within layouts/users
Rendering users/user_details
Completed in 65ms (View: 48, DB: 2) | 200 OK
[http://localhost/user_xml?id=2]
2) With Include:-
def user_details
@user=User.find(params[:id], :include=>:company)
@company=@user.company
end
Log Output:-
Processing UsersController#user_details (for 127.0.0.1 at 2010-08-11
10:53:13) [GET]
Parameters: {"id"=>"2"}
User Columns (1.2ms) SHOW FIELDS FROM `users`
User Load (0.5ms) SELECT * FROM `users` WHERE (`users`.`id` = 2)
Company Load (0.3ms) SELECT * FROM `companies` WHERE
(`companies`.user_id = 2) LIMIT 1
Rendering template within layouts/users
Rendering users/user_details
Completed in 13ms (View: 2, DB: 2) | 200 OK
[http://localhost/user_xml?id=2]
If you look at the both o/p there is a query on company table in both
the cases.