2011-04-13 41 views
1

我使用Rails.cache.write来缓存多个用户对象,但是当我从缓存中检索并尝试调用任何User对象上的属性方法(id,name,email等)时,访问缓存中的对象属性时遇到困难

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? 

我可以调用User对象的检查,并查看所有属性。有任何想法吗?谢谢

我正在使用标准缓存配置,无需修改。下面是一些代码:

我在我的模型,该模型被称为实例方法中,当用户像这样记录以书面形式向缓存:

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

然后在我的控制器I滤波器之前有一个:

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 

我得到if !friend.facebook_id.nil?行的错误。 facebook_id是db中的一列。基本上没有用户实例方法可用于每个用户对象。但我知道这些物体在那里,因为我可以插入raise "#{friends.first.inspect}",并且我所期望的一切都会吐出来。

+0

你可以把代码和缓存配置 – 2011-04-13 18:44:30

+0

编辑一些代码... – jgoggles 2011-04-13 20:15:03

+0

pass:raw => true选项在缓存读取和写入方法,我怀疑加载数据时有问题。希望这会起作用。 – 2011-04-14 04:03:02

回答

1

这发生在开发模式(即设置config.cache_classes = false)。根本原因:

  1. ActiveRecord的条属性存取方法从类对象
  2. MemoryStore的(即,默认缓存存储)不武/ unmartial对象

一个解决方法是使用MemCacheStore都另一一个是设置config.cache_classes = true。另请参阅Comments on railscasts