I have an object with an attribute called value which is of type big decimal. In the class definition i have validates_numericality_of.
However if i:
a.value = 'fire'
'fire' ends up getting typecast to the correct type before the validation fires so:
a.valid? => true
How do get the validation to fire before the typecast?
Thanks
Dan
From ActiveRecord::Base docs:
Sometimes you want to be able to read the raw attribute data without having the column-determined typecast run its course first. That can be done by using the
<attribute>_before_type_cast
accessors that all attributes have. For example, if yourAccount
model has a balance attribute, you can callaccount.balance_before_type_cast
oraccount.id_before_type_cast
.This is especially useful in validation situations where the user might supply a string for an integer field and you want to display the original string back in an error message. Accessing the attribute normally would typecast the string to 0, which isn’t what you want.
A new gem has been created to help validate types in rails.
An explanatory blog post exists to answer more of the "why" it was created in the first place.
With this library your code could be:
class SomeObject < ActiveRecord::Base
validates_type :value, :big_decimal
end
This will throw an exception when anything except a float is assigned to value
instead of quietly casting the value
to a BigDecimal and saving it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With