Forum: Ruby on Rails DB data type enforcement in Active Record

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Wiebe C. (Guest)
on 2006-03-03 18:14
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.
Jason S. (Guest)
on 2006-03-03 18:31
(Received via mailing list)
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
Wiebe C. (Guest)
on 2006-03-03 18:57
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.
Alex Y. (Guest)
on 2006-03-05 12:44
(Received via mailing list)
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?"...
Wiebe C. (Guest)
on 2006-03-05 13:21
Alex Y. wrote:
> Or just "assert object.valid?"...

Indeed, that's cleaner.
This topic is locked and can not be replied to.