Virtual attributes for integer fields

Posted Over 13 years ago. Visible to the public.

Note that this card is very old. You might want to use ActiveType for your auto-coerced virtual attributes Show archive.org snapshot instead.


We sometimes give our models virtual attributes Show archive.org snapshot for values that don't need to be stored permanently.

When such a virtual attribute should contain integer values you might get unexpected behavior with forms, because every param is a string and you don't get the magic type casting that Rails would give you if it was an actual database column. One effect is that when you have form roundtrips due to validation errors, <select> boxes forget their values because "123" does not match 123.

With the attached Modularity Show archive.org snapshot trait you can write this:

does 'integer_field', :group_id

This will create an accessor that casts attribute values to integers if possible, and sets them to nil if they can not be converted.

Henning Koch
Last edit
About 10 years ago
Keywords
fixnum, contain, containing
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2010-11-26 10:23)