validates_numericality_of doesn't work on virtual attribute
If a model has a virtual attribute and has a validates_numericality_of validation on it, calling valide? on it will cause an undefined method `attr_name_before_type_cast’ error.
For example, say we have a Product model, and we have a price attribute for whatever reason that doesn’t persist in database:
class Product < ActiveRecord::Base
attr_accessor :price
validates_numericality_of :price
end
Now we check the validation:
product = Product.new
product.price = "blah"
product.valid?
Oops, we get this:
NoMethodError: undefined method `price_before_type_cast' for #<Product id: nil, name: nil, created_at: nil, updated_at: nil>
Well, it asks for a price_before_type_cast method, let’s give it one:
def price_before_type_cast
self.price
end
Somehow I don’t feel liking this solution. Why validates_numericality_of doesn’t work on a virtual attribute?