ruby on rails -从缓存访问对象属性有问题



我正在使用Rails.cache.write缓存几个用户对象,但是当我从缓存中检索它并尝试在任何用户对象上调用属性方法(id,名称,电子邮件等)时,我正在获得

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对象上调用inspect并看到所有的属性。什么好主意吗?由于

我使用标准缓存配置,没有修改。下面是一些代码:

我在一个实例方法中写入模型中的缓存,该方法在用户登录时被调用,如:

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

然后在我的控制器中我有一个before过滤器:

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中的一列。基本上每个User对象都没有可用的User实例方法。但是我知道对象在那里,因为我可以插入raise "#{friends.first.inspect}",并且一切都像我期望的那样吐出。

这发生在开发模式下(即设置配置。Cache_classes = false)。根本原因:

  1. ActiveRecord从类对象中剥离属性访问器方法
  2. MemoryStore(即默认的缓存存储)不支持军事/非军事对象

一个解决方法是使用MemCacheStore,另一个是设置配置。Cache_classes = true。参见关于railcast的注释

最新更新