consider that i have a migration as follows
create_table :dummies do |t|
t.decimal :the_dummy_number
end
i instantiate like the following
dummy = Dummy.new
dummy.the_dummy_number = "a string"
puts dummy.the_dummy_number
the output for the above is
0.0
how did this happen? since i assign a wrong value shouldn’t it raise an error?
The biggest problem is the following.
Since it automatically converts my validate method fails miserably.
update-the validate method
validate :is_dummy_number_valid, :the_dummy_number
def is_dummy_number_valid
read_attribute(:the_dummy_number).strip()
end
The reason that this does not work as you expect is that the underlying ruby implementation of BigDecimal does not error when passed a string.
Consider the following code
So BigDecimal scans the string and assigns anything at the beginning of the string that could be a decimal to its value.
If you set your model up like this
Then the validation should work fine
This works because the validates_numericality_of macro uses the raw_value method to get at the value before it was typecast and assigned to the internal decimal value.