Topic: Caching find method

Hi,
im trying to cache the following queries. whats the best way to do that? It seems to work fine for User. How would i do the same for List?

thanks

pete


@user = User.find_cached(1)
@list = @user.lists.find([1])

class List < ActiveRecord::Base
  belongs_to :user, touch: true
  has_many :items
end

class User < ActiveRecord::Base
  has_many :lists  
end

CACHING

class List < ActiveRecord::Base
  belongs_to :user, touch: true
  has_many :items

  ???? how would i do this one?
end


class User < ActiveRecord::Base
  has_many :lists  

  def self.find_cached(id)
    Rails.cache.fetch("user/#{id}") { User.find(id) }
  end
end

Re: Caching find method

It's because the method is defined as a self method, this means that it can only be called when calling from the class, not from an instance.

User.find_cached works because the method is a self method. @user.find_cached wouldn't work. So, change your method to:

  def find_cached(id)
    Rails.cache.fetch("user/#{id}") { User.find(id) }
  end

Now, you should be able to access the method through an instance, such as (@user.list.find_cached). However, be sure to add the method to the List class.

Let me know if that works for you

Last edited by wesf90 (2012-04-17 20:16:43)

Remember to edit your topic title and add "[SOLVED]" if your question has been answered!

Follow me!