views:

18

answers:

2

Hi

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

A: 

The typecast happens during the assignment (in this case, the value= method). So there is no way to trigger the validation before that. You will need to sanitize / validate before assigning.

Swanand
+1  A: 

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 your Account model has a balance attribute, you can call account.balance_before_type_cast or account.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.

Mladen Jablanović