Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validation before attribute setters can type cast

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

like image 308
Dan Galipo Avatar asked Sep 22 '10 05:09

Dan Galipo


2 Answers

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.

like image 84
Mladen Jablanović Avatar answered Sep 20 '22 15:09

Mladen Jablanović


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.

like image 35
yez Avatar answered Sep 22 '22 15:09

yez