包含在rails中的优势是什么?

时间:2017-04-29 02:55:57

标签: ruby-on-rails activerecord

我正在学习rails,我发现了包含和加入的新方法。目前我正在使用我的应用程序中的第一个示例,我想知道这种方法的优缺点。有人可以帮帮我吗?

示例=

@comments = Comment.includes(:post)
or 
@commens = @post.comments

2 个答案:

答案 0 :(得分:0)

.includes帮助您改进数据库查询(往返)

当您执行简单查询时,请执行以下操作:

@comments = Comment.all

Rails创建一个数据库查询来获取所有注释。

当你在视图中有需要另一个数据库表的内容时(例如发布)

@comments.each do |comment|
  comment.post.title   // get the post title to which the comment belongs
end

现在,rails必须对每个评论进行单独查询,以获得相关帖子。像这样:

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.

这会导致数据库的多次往返,这取决于数据库的大小和记录的数量,可能非常慢。那时.include进来了:

@comments = Comment.all.includes(:post)

而不是几次往返,它只做2:

  1. 获取所有评论
  2. 获取所有评论的帖子
  3. Rails发送一个包含所有注释id的数组,让数据库可以轻松找到与id匹配的所有帖子:

    Find post where comment id is [1,2,3,etc.] (1ms)
    

    而不是

    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)
    

    非常酷。你可以尝试一下。使用和不使用.include运行查询并比较您在开发中的日志,它们会缩小很多,您可以看到rails花费了多少时间实际获得每个帖子和评论。它有时会缩短响应时间。

答案 1 :(得分:0)

join和include之间的区别在于,使用include语句会生成一个更大的SQL查询,将来自其他表的所有属性加载到内存中。

例如,如果您有一个充满评论的表格,并使用:joins =>用户可以提取所有用户信息以进行排序等,它可以正常运行并且花费的时间少于:include,但是您要显示注释以及用户名,电子邮件等。要使用以下内容获取信息:join ,它必须为它提取的每个用户分别进行SQL查询,而如果你使用:include这个信息可以使用了。

很好的例子:

http://railscasts.com/episodes/181-include-vs-joins