Rails method_missing and activerecord class caching
We're using method_missing
to load attributes from a serialized hash. For example, given a model:
model = { :name => 'name',
:options => { :title => 'title',
:custom_field => 'field1',
:custom_field => 'field2' } }
and a stripped-down version of our method_missing
(it does some other stuff to check that the option is allowed and calls super of course if the option isn't found):
def method_missing(method, *args)
self.options[me开发者_如何学运维thod]
end
then the attribute is gotten using model.custom_field
In development environment, this works for the first page load but any subsequent page load errors out with "undefined method 'custom_field'".
I think that I have read that this is an issue with activerecord class caching, but I'm having trouble finding where I saw that before.
Is there a known way to fix this issue?
Instead of whatever self.options
is, use an instance variable to store the hash and return from it.
def method_missing(method, *args)
return @serialized_hash[method] if @serialized_hash.include?(method)
super
end
It's not ActiveRecord that caches classes, it's Rails. It does so in the production environment. In development, it'll reload your models on every request and thus overwrite any runtime modifications you've made in the prior request.
精彩评论