Rails中的低级缓存4 [英] Low level caching in rails 4

查看:110
本文介绍了Rails中的低级缓存4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有员工和组织两个模型

I have two models Employee and Organization

class Employee < ActiveRecord::Base
  belongs_to :organization, touch: true
end

class Organization < ActiveRecord::Base
  has_many :employees
end

有一种用于搜索员工的表格.

There is a form which is used to search the employees.

搜索查询基于first_name,last_name和emp_id.

The search query is based on first_name, last_name and emp_id.

我正在尝试实现低级缓存

在员工控制员中

def list_employees
  first_name = params[:employee][:first_name]
  last_name  = params[:employee][:last_name]
  emp_id     = params[:employee][:emp_id]
  @employees = Employee.all_employees(first_name,last_name,emp_id)
end

在员工模型中

def self.all_employees(first_name,last_name,emp_id)
  cache_key = "#{first_name}-#{last_name}-#{emp_id}"
  Rails.cache.fetch("#{cache_key}", expires_in: 5.minutes) do
    Employee.where("first_name like ? and last_name like ? and emp_id like ?","%#{first_name}%","%#{last_name}%","%#{emp_id}%")
  end
end

但是每次重新查询时我都看不到任何区别.我可以看到数据从控制台访问Rails.cache.fetch("cache_keys"),甚至查询员工表.

But i cant see any difference each time its querying again. I can see data Rails.cache.fetch("cache_keys") from console even here its querying to employee table.

第一次查询时需要500毫秒第二次相同的查询需要490毫秒(不从缓存中投放)

First time when i query it takes 500ms Second time same query it takes 490ms (not serving from cache)

让我知道我在做错什么.

Let me know what i am doing wrong.

预先感谢

推荐答案

这是您存储为缓存值的内容:

This is what you store as your cached value:

Employee.where("first_name like ? and last_name like ? and emp_id like ?","%#{first_name}%","%#{last_name}%","%#{emp_id}%")

这不是员工列表,仅是有关如何找到员工的信息.因此,当您以后从缓存中检索该对象时,您每次都会运行查询以获取员工.

This is not a list of employees, this is only information on how to find the employees. So when you later retrieve this object from the cache, you run the query every time, to get the employees.

在缓存时通过向其附加 .to_a 来运行查询.这将返回一组员工,这就是您要缓存的内容.

Run the query when caching, by appending .to_a to that. This will return an array of employees, which is what you want to cache.

这篇关于Rails中的低级缓存4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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