devroom.io/drafts/2008-04-09-rails-snippet-caching-expensive-calls.md
Ariejan de Vroom dbae98c4c0 Moar updates
2013-03-24 14:27:51 +01:00

1.4 KiB

title kind slug created_at tags
Rails Snippet: Caching expensive calls article rails-snippet-caching-expensive-calls 2008-04-09
General
RubyOnRails
Ruby
Rails
snippet

In Rails, from time to time, you may encounter you have a method you call several times, but which returns always the same result. For example, have the following:

class Person < ActiveRecord::Base
  has_many :articles

  def get_approved_articles
    self.articles.find(:all, :conditions => {:approved => true}, :order => 'approved_on DESC')
  end
end

A query is fired every time you call Person#get_approved_articles. To cache the result of the query during this request, just add a bit of magic

class Person < ActiveRecord::Base
  has_many :articles

  def get_approved_articles
    @approved_articles ||= self.articles.find(:all, :conditions => {:approved => true}, :order => 'approved_on DESC')
  end
end

This will return the @approved_articles value if it exists. If it doesn't, which is the first time you access the method, the query is run and stored in @approved_articles for later use.

Note: I know it's much easier to define this kind of behaviour, but it's just an illustration.

class Person < ActiveRecord::Base
  has_many :articles
  has_many :approved_articles, :class_name => "Article", :conditions => {:approved => true}, :order => 'approved_on DESC'
end