rails + ActiveRecord:缓存模型的所有寄存器 [英] rails + ActiveRecord: caching all registers of a model

查看:99
本文介绍了rails + ActiveRecord:缓存模型的所有寄存器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很小的模型(我们称其为节点"),它代表一个树状结构.每个节点仅包含一个名称和对其父节点的引用:

I've got a tiny model (let's call it "Node") that represents a tree-like structure. Each node contains only a name and a reference to its father:

class Node < ActiveRecord::Base
  validates_presence_of :name, :parent_id
end

表不是很大-少于100个元素.它很少更新-在过去的四个月中,网站管理员一次添加了20个新元素.

The table isn't very big - less than 100 elements. It's updated rarely - in the last 4 months 20 new elements were added, in one occasion, by the site admin.

然而,它在我的应用程序中已被大量使用.鉴于其树状结构,在某些情况下,请求会触发30多次数据库匹配(包括ajax调用,我使用了很多).

Yet it is used quite a lot on my application. Given its tree-like structure, on some occasions a request triggers more than 30 database hits (including ajax calls, which I use quite a lot).

我想使用某种缓存来降低对数据库的访问-由于表太小,我考虑过将所有寄存器缓存在内存中.

I'd like to use some sort of caching in order to lower the database access - since the table is so small, I thought about caching all registers in memory.

这可能是Rails 2.3吗?有更好的方法来解决这个问题吗?

Is this possible rails 2.3? Is there a better way to deal with this?

推荐答案

为什么不每次都全部加载它们以避免被多次加载击中?

Why don't you just load them all every time to avoid getting hit with multiple loads?

这是一个简单的例子:

before_filter :load_all_nodes

def load_all_nodes
  @nodes = Node.all.inject({ }) { |h, n| h[n.id] = n; n }
end

这将为您提供一个由Node#id索引的哈希,因此您可以使用此缓存代替查找调用:

This will give you a hash indexed by Node#id so you can use this cache in place of a find call:

# Previously
@node = Node.find(params[:id])

# Now
@node = @nodes[params[:id].to_i]

对于小的,简单的记录,一次读取即可快速加载它们是一项相当便宜的操作.

For small, simple records, loading them in quickly in one fetch is a fairly inexpensive operation.

这篇关于rails + ActiveRecord:缓存模型的所有寄存器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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