0

I'm currently learning rails and I found new methods which are includes and joins. Currently I'm using the first example in my app, and I would like to know the advantages or disadvantages of this methods. Anyone can help me ?

Examples =

@comments = Comment.includes(:post)
or 
@commens = @post.comments
jacques Mesnet
  • 607
  • 3
  • 10

1 Answers1

0

.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:

  1. Get all the comments
  2. 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.

Alexander Luna
  • 5,261
  • 4
  • 30
  • 36
  • Thanks you very much for your answer Alex, is much more clear now. It's a little bit tasty at the begging but now it's sounds really good – jacques Mesnet Apr 29 '17 at 06:19
  • But be careful if there are a lot of records because depending the number it will bring your app down (ex. use it in a restricted and known number of records vs .all) – s1mpl3 May 07 '17 at 18:24
  • s1mpl3 true, usually you will have some sort of pagination mechanism which pulls out a limited number of posts not all at the same time. – Alexander Luna May 08 '17 at 00:10