Search code examples
ruby-on-rails-3memcacheddalli

Rails.cache.fetch inserting extra values


We have a page which shows the top groups for our application. The calculation of the leader board is expensive so we cache the results for an hour as follows:

@groupboard = Rails.cache.fetch("top_groups", :expires_in => 1.hour) do  
  Group.top_groups
end

This is giving an error after the cache has been written the first time. Poking around in the console I see that Group.top_groups returns an array of items that look as follows:

[#<Group id: 4, name: "IBP", rank: 6, users_count: 13, leader_id: 4662>, 3887]

When I look at the result returned from the cache it looks as follows:

[#<Group id: 4, name: "IBP", rank: 6, users_count: 13, leader_id: 4662>, :@new_record_before_save], false, 3887]

Does anyone know what would be causing @new_record_before_save and the 'false' value to be inserted into all the entries for this object in the cache?

We are using Dalli, Memcached 1.4.9, Rails 3.2.4, Ruby 1.9.2


Solution

  • There is a bug of Rails cache on AR object which has associated object. Try following:

    @groupboard = Rails.cache.fetch("top_groups", :expires_in => 1.hour) do  
      Group.top_groups.map(&:reload)
    end
    

    see more on https://github.com/mperham/dalli/issues/250