Virtual attributes for date fields

Posted Almost 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 Date 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. E.g. when you set an ActiveRecord date field to '10.05.2011' it will automatically parse that to a Date instance, and when you set it to an empty string, it will set the field to nil.

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

does 'date_field' :start_date

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

Henning Koch
Last edit
About 10 years ago
Attachments
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2011-07-19 19:36)