Rails 5.2.1-模型和片段缓存 [英] Rails 5.2.1 - Model & Fragment Caching

查看:88
本文介绍了Rails 5.2.1-模型和片段缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Rails 5.2.1中设置模型和片段缓存

I am trying to setup Model and Fragment Caching in Rails 5.2.1

我已经成功地使用了片段缓存,但是在为我的模型实现模型缓存之后,我仍然看到数据库查询.

I have had success with Fragment caching, but I am still seeing database queries after implementing model caching for my Model.

我启用了开发缓存

$ rails dev:cache

模型助手

module LanguagesHelper
  def approved_languages
    Rails.cache.fetch("approved_languages") { Languages.is_active.is_approved }
  end
end

控制器

class LanguagesController < ApplicationController
  include LanguagesHelper

  def index
    @languages = approved_languages
  end
end

观看次数

app/views/languages/index.html.erb

<%= render partial: 'languages/language', collection: @languages, cached: true %>

app/views/languages/_language.html.erb

<% cache language do %>
  <%= language.name %>
<% end %>

控制台

Started GET "/languages" for 127.0.0.1 at 2018-08-21 14:13:29 -0400
Processing by LanguagesController#index as HTML
  Rendering languages/index.html.erb within layouts/application
  Language Load (1.2ms)  SELECT "languages".* FROM "languages" WHERE "languages"."deleted" = $1 AND "languages"."approved" = $2  [["deleted", false], ["approved", true]]
  ↳ app/views/languages/index.html.erb:4
  Rendered collection of languages/_language.html.erb [1 / 1 cache hits] (3.0ms)
  Rendered languages/index.html.erb within layouts/application (10.9ms)
Completed 200 OK in 50ms (Views: 46.2ms | ActiveRecord: 1.2ms)

为什么我仍会在每个请求中看到数据库查询?

Why am I still seeing database queries with each request?

推荐答案

我之前已经关闭,但是现在已经成功实现了缓存.上面的答案是值得赞赏的,但不是我想要的,这是我当前的设置.

I was close before but now have successfully implemented caching. The above answer was appreciated but not what I was looking for, this is my current setup.

当我应该将其移至模型时,我正在Helper模块中调用语言模型查询.

I was calling the Language model query in a Helper module when I should have moved it to the model.

模型

after_save :clear_cache
after_destroy :clear_cache

def clear_language_cache
  Rails.cache.delete('Language.active.approved')
end

def self.active_approved
  Rails.cache.fetch('Language.active.approved') { is_active.is_approved.order(created_at: :desc).to_a }
end

控制器

class LanguagesController < ApplicationController
  def index
    @languages = Language.active_approved
  end
end

控制台

Started GET "/languages" for 127.0.0.1 at 2018-08-22 18:13:21 -0400
Processing by LanguagesController#index as HTML
  Rendering languages/index.html.erb within layouts/application
  Rendered collection of languages/_language.html.erb [1 / 1 cache hits] (11.0ms)
  Rendered languages/index.html.erb within layouts/application (15.9ms)
Completed 200 OK in 68ms (Views: 45.5ms | ActiveRecord: 5.8ms)

这篇关于Rails 5.2.1-模型和片段缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆