jgoggles
jgoggles

Reputation: 53

Trouble accessing object attributes from cache

I am caching several User objects using Rails.cache.write but when I retrieve it from cache and try to call an attribute method (id, name, email, etc.) on any of the User objects I am getting

You have a nil object when you didn't expect it! 
You might have expected an instance of Array. 
The error occurred while evaluating nil.include? 

I can call inspect on the User objects and I see all the attributes. Any ideas? Thanks

I'm using the standard cache configuration, no modification. Here is some code:

I am writing to the cache in my model inside an instance method that gets called when the user logs in like so:

cached_friends = self.friends
Rails.cache.write(self.id.to_s+"_friends", cached_friends)

Then in my controller I have a before filter:

def get_friends_from_cache
  if current_user
    friends = Rails.cache.read(current_user.id.to_s+"_friends")
    friends.each do |friend|
      if !friend.facebook_id.nil?
        #other stuff....
      end
    end
  end
end

I get the error on the if !friend.facebook_id.nil? line. facebook_id is a column in the db. Basically there are no User instance methods available for each User object. But I know the objects are there because I can insert raise "#{friends.first.inspect}" and everything spits out as I would expect.

Upvotes: 1

Views: 291

Answers (1)

Joachim Büchse
Joachim Büchse

Reputation: 26

This happens in development mode (i.e. with the setting config.cache_classes = false). The root cause:

  1. ActiveRecord strips the attribute accessor methods from the class objects
  2. MemoryStore (i.e. the default cache store) does not martial/unmartial objects

One workaround is to use MemCacheStore another one is to set config.cache_classes = true. See also Comments on railscasts

Upvotes: 1

Related Questions