.includes helps you improve database queries (roundtrips)
When you do a simple query likes this:
@comments = Comment.all
Rails creates one database query to fetch all the Comments.
When you have in your view something that requires another database table's content (ex. Post)
@comments.each do |comment|
comment.post.title // get the post title to which the comment belongs
end
Now rails has to do separate queries for each comment to also get the associated post. Something like this:
Find post where comment id is 1 (0.5ms)
Find post where comment id is 2 (0.5ms)
Find post where comment id is 3 (0.5ms)
# and so on.
This results in multiple round trips to the database which depending on the size of the database and the amount of records, can be VERY slow. That is when .include comes in:
@comments = Comment.all.includes(:post)
Instead of doing several round trips it only does 2:
- Get all the comments
- Get all the comment's post
Rails sends an array containing all the comments id and lets the database do the heavy lifting of finding all the posts that match the id's:
Find post where comment id is [1,2,3,etc.] (1ms)
instead of
Find post where comment id is 1 (0.5ms)
Find post where comment id is 2 (0.5ms)
Find post where comment id is 3 (0.5ms)
It is pretty cool. You can try it out. Run a query with and without .include and compare your logs in development they will shrink by a lot and you can see how much time rails spends actually getting each post and comment. It improves response times by quite a bit sometimes.