包括在铁轨中的优势是什么?



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

示例=

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

。包括帮助您改进数据库查询(往返(

当您进行简单查询时,会喜欢以下内容:

@comments = Comment.all

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

当您在视图中具有需要另一个数据库表的内容(例如,post(

@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. 获取所有评论的帖子

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)

这很酷。您可以尝试一下。在有和不包含的情况下运行查询,并比较您的开发日志,它们会缩小很多,您可以看到Rails花费了多少时间实际获取每个帖子并发表评论。有时会改善响应时间。

相关内容

最新更新