Rails4:型号缓存(低级别的缓存) [英] Rails4 : Model caching (low level caching)

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

问题描述

我想活动记录的查询缓存结果。

I am trying to cache results of Active Record Query.

下面是我的使用情况:

User.rb
  def self.awesome_users_cached
    Rails.cache.fetch("awesome_users") { where(awesome: true) }
  end

UsersController
  def index
    all_awesome_users  = User.awesome_users_cached
    less_awesome_users = User.where(less_awesome_user:true).pluck(:id)
    @users             = all_awesome_users.where.not(id: less_awesome_users)
  end

下面有2个问题:

  1. self.awesome_users_cached犯规缓存结果,并最终击中
  2. all_awesome_users结束了作为一个数组,而不是活动记录,所以我不能从中筛选出less_awesome_users。

有那不解决似乎在Rails4工作了: Rails的缓存,where子句

There was a solution that doesnt seem to work in Rails4 anymore: Rails cache with where clause

推荐答案

您永远不应该缓存ActiveRecord的情况下,或者在一般的复杂对象。相反,你应该缓存简单的原始值,如记录的主键。

You should never cache ActiveRecord instances, or complex objects in general. Rather, you should cache simple primitive values, such as the primary keys of the records.

在你的情况,还有一个问题。 其中(真棒:真)返回一个范围,而不是一个查询结果。由于范围是懒惰执行,将有效地从不缓存任何东西,但总是执行查询。

In your case, there is one more issue. where(awesome: true) is returning a scope, not a query result. Because the scope is lazy-executed, you effectively never cache anything but the query is always executed.

。然后进行第二次查询,通过ID获取这些记录。您将运行2的查询,但第一个(最便宜的一种)会后的第一次被缓存。

If you want to cache the lookup, execute the heavy query and return the IDs of the affected records. Then perform a second query fetching the records by id. You will be running 2 queries, but the first one (the most expensive one) will be cached after the first time.

def self.awesome_users_cached
  ids = Rails.cache.fetch("awesome_users") { where(awesome: true).pluck(:id) }
  find(ids)
end

您可以缓存第一个查询的查询,但正如我前面提到它是不是一个好主意。

You can cache the lookup of the first query, but as I mentioned before it is not a good idea.

def self.awesome_users_cached
  Rails.cache.fetch("awesome_users") { where(awesome: true).to_a }
end

您也可以使用不同的查询方法,让您可以轻松地链附加条件,以缓存的查询。

You can also use a different query approach so that you can easily chain additional conditions to the cached query.

def self.awesome_users_cached
  ids = Rails.cache.fetch("awesome_users") { where(awesome: true).pluck(:id) }
  where(id: ids)
end

awesome_users_cached.where.not(id: same_company_users)

这篇关于Rails4:型号缓存(低级别的缓存)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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