Aaron Van Bokhoven

I am a Hawaii based Software Developer and a Film Photographer.
  • I guess you could call me a "full stack developer".
  • I love coding with Ruby and Ruby on Rails, and I love shooting with film.
  • I have a love/hate relationship with Ember.js, and Backbone.js.
  • I currently live in Honolulu, Hawaii, but frequent Chicago and California.
  • I believe that programming is a form of art, like painting and photography, where you can express your ideas and logic and see it transform into something real.
Aaron Van Bokhoven
Email me at bokhoven@gmail.com. View my Photo Blog. I'm also on Twitter.

July 17, 2011
You're viewing an article, go back to the home page to see more.

Note: This doesn't affect anything in production as classes are cached at load, see config/environments/production.rb: config.cache_classes = true

I've run into this annoying little problem every time I start work on implementing caching into my rails projects using the built in Rails.cache in Activerecord. If you are using Rails.cache, and you are using it to store objects using Marshal.dump and Marshal.load, which is default, I'm sure you've experienced this error. I'm also pretty sure you've googled it and were a little confused as to why it keeps happening.

You write an object to the Rails.cache, Rails.cache.write("post_#{@post.id}", @post), and then read the object, Rails.cache.read("post_#{@post.id}"), you get the object. Now this time you write the object to cache, restart your rails app, and try to read the object, but now you've received an error, ArgumentError: undefined class/module YOUR_MODEL. This is because rails is trying to Marshal the object, or model in this case, but rails hasn't loaded the model yet!

Go ahead, test it:

So the solution is to just load all the damn models at load. I thought about using the production value, config.cache_classes = true, in the development environment, but then I would have to restart my server every time I modified any code. Then I thought why can't I just require it in an initialize file that only runs if it's in development mode.

Create a file in your config/initializers folder and put this in:



© Aaron Van Bokhoven