您好我正在尝试在memcached中缓存查询结果,但遗憾的是我无法执行此操作,因为该对象是ActiveRecord :: OrderedHash对象:
result = Car.where(:brand => 'BMW').order(:model_name).group(:model_name).count(:model_name)
#=> {'120d' => 23, '316i' => 3, '525d' => 50} which is a ActiveRecord::OrderedHash if i ask .class
Rails.cache.write('cached_result', result)
这会返回以下错误:
键'cached_result'的编组错误:无法使用默认proc转储哈希 您正在尝试缓存无法序列化为memcached的Ruby对象。 /Users/nk/.rvm/gems/ruby-1.9.3-p194@au/gems/dalli-2.1.0/lib/dalli/server.rb:277:in"dump'
解决这个问题的最佳/最简单的做法是什么?
答案 0 :(得分:0)
这应该可以解决问题。由于to_hash
方法也返回OrderedHash
对象,而不是Hash
对象,因此必须采用不同的路径:
result = Car.where(:brand => 'BMW').order(:model_name).group(:model_name).count(:model_name)
# make a simple array of the OrderedHash and put it in a "normal" one
h = Hash[result.to_a]
h.class # => Hash