Saturday, June 30, 2007

Rails + Memcached = Undefined Class/Module

Problem:

When using memcached, if you store Model objects in the cache, when you go to load to object back out it doesn't know about your Model classes and throws an 'Undefined Class/Module' error. The old solution for this was to add the 'model' method to the top of your controller and list the models that were needed. This is now deprecated.

Solution:

before_filter  :preload_models
 
def preload_models()
  Model1
  Model2
  ...
  ...
  ...
  Model9
end

What it do?

This is more of a hack than a solution, but it works. Add the above code to your application controller and list all the models you are storing in memcached as well as any associations that are also being stored. Referencing the Model class name must trigger a load that loading from memcached does not.

6 comments:

Saravanan said...

Thanks PHIL... Its works..

RevathyM said...

Hi Phil,

Thank you for your memcache solution.

It works fine .

bbn said...

The proper way to solve this issue is with require_dependency.

require_dependency 'model.rb'

kball said...

If you're still interested in this problem, I posted about a less hacky solution here.

blabalbasd said...

If somebody still has problems here is also a solution

http://stackoverflow.com/questions/3531588/memcached-as-an-object-store-in-rails

Krishna Rani Sahoo said...

Hi Phil

Its working fine. I have another question. After implemention of preload_models(), will it take extra execution time?

Thanks