Stupid mistakes and helpful hints
I'm English. Which means I spell English and not Yank.
This also means that I waste hours of my precious time wondering why my constructor is not working when in fact I have written
def initialise(params = nil)
super
do_whatever
end
Spot the error?
When using Single Table Inheritance and overriding validate, don't forget to call super in your descendant class, otherwise validate doesn't get called in your super-class. Obvious but it has caught me out.
And lastly, if you are using attr_accessor to create "temporary" attributes and you want to use validations on them, you will find you get a "NoMethodError: undefined method `my_attribute_before_type_cast' for Whatever". However, the following method (adapted from Rails Recipes - recipe 64) will fix it:
def method_missing(symbol, *params)
if (symbol.to_s =~ /^(.*)_before_type_cast$/)
send $1
else
super
end
end
Basically, any method call ending in "_before_type_cast" will be re-sent without the suffix - so calling your temporary accessor itself.
Incidentally, I can't get Recipe 64 to work with Rails 1.1.6 (not tried with Rails 1.2.1), which is why I came up with the Pseudo-Model trick.
3 comments:
Actually the error I spotted was the misspelling of initialiZe ;)
Aye ... initialize is American, initialise is English ...
Just noticed I used the English spelling all the way through my "default values" (http://made-of-stone.blogspot.com/2007/01/default-values-in-your-models.html) article.
Post a Comment