美文网首页
2018-08-13-加速提早加载 和 计数缓存

2018-08-13-加速提早加载 和 计数缓存

作者: 护念 | 来源:发表于2018-08-13 22:07 被阅读0次

    includes 提早加载

    提早加载是为了解决n + 1 查询问题:
    问题描述:

    一个作者,有许多本书,这是一个一对多的关系;当我们一次性取出,所有作者,然后遍历作者,并取出它们的书,这时就会查询n + 1 次。

    authors = Author.all
    
    authors.each do |author|
      puts author.books.size
    end
    
    image.png
    解决办法:其实挺简单,用includes 方法就好。
    authors = Author.includes(:books).all
    效果
    image.png

    counter_cache 计数缓存

    问题描述:

    一篇文章,有多个评论。一对多的关系,我需要知道每篇文章的评论数,就必须通过关联,article.comments.length 去查询。
    这也比较慢,计数缓存的解决办法是,把评论数缓存到articles表中,每次新增评论,rails 会自动去更新articles 中的 计数字段(comments_count)
    用法:

    class Article < ApplicationRecord
      has_many :comments
    end
    
    class comments < ApplicationRecord
      belongs_to :article, counter_cache: true # 这里打开
    end
    
    # artilces 中新增 计数字段
    add_column :articles, :comments_count, :integer,default: 0,null: false
    

    PS: 字段名:另一张表名_count

    相关文章

      网友评论

          本文标题:2018-08-13-加速提早加载 和 计数缓存

          本文链接:https://www.haomeiwen.com/subject/xcjpbftx.html