2012-10-04 288 views
4

我在控制器中设置了这两个变量。我如何缓存这些数据,以便它们不会每次都只与第一次与数据库通信。Ruby on Rails - 缓存变量

@tablenutrients = Nutrient.find(:all) 
@columnnutrients = @tablenutrients.collect {|x| x.nutrient} 

回答

10

@djlumley说什么。

通常,您还可以配置和使用ActiveSupport::Cache::Store来显式存储您自己的自定义变量。然后,您可以获取/设置缓存的值,例如,像这样:

@tablenutrients = Rails.cache.fetch("tablenutrients") do 
    Nutrient.find(:all) 
end 
+0

感谢您的回答 –

3

如果你的数据库设置正确,它应该默认缓存你的数据。如果您使用的是MySQL或postgresql,则可以更改缓存使用的RAM数量,以确保获得高缓存命中率。

除了简单的数据库缓存之外,使用类似Dalli连接到memcached应​​该使改进性能相当容易。

Rails应该利用memcached缓存memcached中的所有活动记录查询,只要它正确设置即可。 Rails guide on caching加上Dalli documentation应该可以帮助您根据您运行的Rails版本开始工作。

+0

感谢您的意见。我会仔细看看的。 –

2

Rails有内置在你的缓存选项,其中两个会为你这取决于你用什么做的工作可能,几查询结果:

片段缓存

如果您正在使用这个作为一个选择框经常使用的形式,我会用这个选项去收集。这将允许您不仅缓存数据库结果,而且缓存页面的实际HTML部分。这是通过抛出一个<%= cache do %>周围的部分简单地完成,就像这样:

<html> 
    ... 
    <body> 
    ... 
    <div class='content'> 
     ... 
     <%= cache do %> 
     <%= select "nutrient", "nutrient", Nutrient.all.collect(&:nutrient) } %> 
     <% end %> 

Rail.cache

你也可以写一个方法通过降低一个直接对话的内置缓存存储,,然后在ApplicationController的方法有它的一个的before_filter回调运行,像这样:

application_controller.rb

class ApplicationController < ActionController::Base 
    before_filter :retrieve_nutrients 

    def retrieve_nutrients 
    @nutrients = Rails.cache.fetch("nutrients") do 
     Nutrient.all.collect(&:nutrient) 
    end 
    end 
end 

在生产环境中这两种情况下,你会想设置任何的Memcached或Redis的作为一个缓存层(他们坐在后面Rails.cache并实施SNAP)。我会结账Rails Guides以深入了解它。

+0

感谢您的信息我欣赏它 –