Getting error Can't Modify Frozen Object while using memcached in Rails

I'm having a problem with memcached.

I'm using the example by Gregg Pollack here http://railslab.newrelic.com/2009/02/19/episode-8-memcached

post.rb

def self.recent
    Rails.cache.fetch('recent_posts', :expires_in => 15.minutes) do
        self.order('id DESC').limit(15)
    end
end

In my controller I call it with @posts = Post.recent and it's written to the cache. If I reload the page I get the error TypeError: can't modify frozen object.

I tried the same thing in the console and I get the same error. The first time I execute @posts = Post.recent, the key recent_posts is added to the cache. When I execute the same command the second time, I get the frozen error.

I'm using Rails 3.0.1 and working in development mode.

Am I doing something wrong here?

Thanks!

Tim

Answers


You are caching sorting options, not any actual results. When you perform the query, Rails will modify your query options, which won't work, because something from cache is considered immutable.

Try this:

def self.recent
  Rails.cache.fetch('recent_posts', :expires_in => 15.minutes) do
    self.order("id DESC").limit(15).all
  end
end

Now you'll store an array of posts, which you can later use.


Need Your Help

video/audio doesnt seem to work on safari?

video html5 audio safari

I grabbed this example from apples website

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.