Hi i’m trying to cache a query result in memcached but unfortunately I’m unable to do it, because the object is an ActiveRecord::OrderedHash object:
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)
This returns me the following error:
Marshalling error for key ‘cached_result’: can’t dump hash with default proc
You are trying to cache a Ruby object which cannot be serialized to memcached.
/Users/nk/.rvm/gems/ruby-1.9.3-p194@au/gems/dalli-2.1.0/lib/dalli/server.rb:277:in `dump’
What is best/simplest practice to solve this?
This should probably do the trick. Since the
to_hashmethod also returns aOrderedHashobject, and not aHashobject, one has to take a different route: