DB data type enforcement in Active Record


#1

I have a question about how ActiveRecord handles data types.

When I enter text in a text_field (meaning, a field in the GUI) which
belongs to a numeric field in the database, Active Record automaticly
converts it to 0, because that’s what the to_f/to_i method of a string
does. Is it also possible to have Active Record enforce the types, so
that when you enter text for a numeric field, it generates an exception?
A solution which doesn’t involve specifing a method in each model to
manually check for types would be nice…

Thanks in advance.


#2

On 03/03/06 17:14 +0100, Wiebe C. wrote:

I have a question about how ActiveRecord handles data types.

When I enter text in a text_field (meaning, a field in the GUI) which
belongs to a numeric field in the database, Active Record automaticly
converts it to 0, because that’s what the to_f/to_i method of a string
does. Is it also possible to have Active Record enforce the types, so
that when you enter text for a numeric field, it generates an exception?
A solution which doesn’t involve specifing a method in each model to
manually check for types would be nice…

What you’re looking for is present with Validations. See
validates_numericality_of.

Regards,
Jason


#3

Jason S. wrote:

What you’re looking for is present with Validations. See
validates_numericality_of.

Haha, of course. I wanted to use this for my unit tests as well,
therefore was looking for a way to get an exception. But I can test
“assert ! object.save”, since it isn’t saved when it doesn’t match the
validation.

On a sidenote, is there a good way to let AJAX forms pick up on
validation? Currently, it just does nothing, it fails silently.


#4

Wiebe C. wrote:

But I can test
“assert ! object.save”, since it isn’t saved when it doesn’t match the
validation.
Or just “assert object.valid?”…


#5

Alex Y. wrote:

Or just “assert object.valid?”…

Indeed, that’s cleaner.