【发布时间】:2017-11-07 12:27:51
【问题描述】:
我有两个模型 Employee 和 Organization
class Employee < ActiveRecord::Base
belongs_to :organization, touch: true
end
class Organization < ActiveRecord::Base
has_many :employees
end
有一个表格用于搜索员工。
搜索查询基于 first_name、last_name 和 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") 从控制台甚至在这里查询员工表。
我第一次查询需要 500 毫秒 第二次相同的查询需要 490 毫秒(不从缓存中提供服务)
让我知道我做错了什么。
提前致谢
【问题讨论】:
-
代码中真的有
emp-id吗?如果这不是您的实际代码,那么您在简化问题时可能错过了关键细节 -
如果您在 fetch 调用中执行
Employee.where("first_name like ? and last_name like ? and emp_id like ?","%#{first_name}%","%#{last_name}%","%#{number}%").to_a会有所不同吗?注意尾随.to_a -
虽然我错过了构建问题,但我已更正了 emp_id。我会尝试 .to_a,但我很困惑为什么缓存不起作用
-
我怀疑您实际上并没有将数据存储在那里。只有查询。
-
我添加了 .to_a 并从控制台检查它的速度更快,他们没有在 rails doc 中提到任何地方,谢谢。你能解释一下它的作用吗,我也有分页,它不能在数组上工作
标签: ruby ruby-on-rails-4 caching