开发者

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 i开发者_运维技巧t 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


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.


Note that if you're doing this in Rails 3 that because Rails now lazy loads, arel is being used to fetch the records. So all you're storing is technically an active record relation.

So you need to address this issue before storing in memcached a la the .to_a method on the arel. This will make it an array before storing the object.

i.e. @posts = Post.recent.to_a

Hope this helps someone.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜