rails + ActiveRecord:缓存模型的所有寄存器(rails + ActiveRecord: caching all registers of a model)

17 IT屋

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

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.

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.

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?

Here's a simple example:

before_filter :load_all_nodes

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

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.

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



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


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



不过,在我的应用程序中已经使用了很多。鉴于其树状结构,在某些情况下,请求会触发30多个数据库匹配项(包括ajax调用,我使用了很多)。



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



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


解决方案

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



这是一个简单的示例:



  before_filter: load_all_nodes 

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


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



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

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


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


本文地址:IT屋 » rails + ActiveRecord:缓存模型的所有寄存器