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.
8a00145d61d84b58c4688cdc50bac48f?d=identicon&s=25 Wiebe Cazemier (halfgaar)
on 2006-03-03 17: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.
6372e690497a80453a1d3d120d8b8818?d=identicon&s=25 Jason Stewart (Guest)
on 2006-03-03 17:31
(Received via mailing list)
On 03/03/06 17:14 +0100, Wiebe Cazemier 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
8a00145d61d84b58c4688cdc50bac48f?d=identicon&s=25 Wiebe Cazemier (halfgaar)
on 2006-03-03 17:57
Jason Stewart 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.
Ad7805c9fcc1f13efc6ed11251a6c4d2?d=identicon&s=25 Alex Young (Guest)
on 2006-03-05 11:44
(Received via mailing list)
Wiebe Cazemier 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?"...
8a00145d61d84b58c4688cdc50bac48f?d=identicon&s=25 Wiebe Cazemier (halfgaar)
on 2006-03-05 12:21
Alex Young wrote:
> Or just "assert object.valid?"...

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