Nicolas B. wrote:
My problem is that Form helpers like text_field, text_area, etc, don’t
seem to work with these custom accessors, is that normal ?
Yes, this is normal. And for whatever it’s worth, I’ve learned and
forgotten this at least 3 times - since I’m thinking in pure OO mode
most of the time and I expect overridden methods to get called.
Because you can do complex transformations in a custom attribute reader,
Rails gets the attribute value using _before_type_cast.
One way to think about the reason for this is because Rails has no
built-in notion of a model of the form’s state (what in the J2EE world
might be called a “form bean”). Because the default behavior of the
ActiveRecord/controller/view interaction is to read/write attributes
directly from the DB to/from the view, there’s no facility to keep track
of what’s going on the form during unsuccessful attempts to save a
particular attribute (e.g. what was typed into the form field when it’s
In effect, you end up using a custom attribute reader/writer pair to
manage this form state. If you take the set of all such methods that
you end up writing on your ActiveRecord object, you would see that they
basically represent a “form state” or “form model” object, even though
they are methods on the model.
I’ve been thinking about this a lot. Take a look at the ActiveForm
plugin for one way to formalize this “form model” notion. In cases
where the form state can be complex, a separate form model would keep
your form state straight, but then would imply a copying step from the
form model attributes into the model attributes and the opposite.
If most of your model attributes don’t need tweaking to be displayed,
then just adding a couple of custom attribute reader/writer pairs is
But I think it’s helpful to keep the distinction between form data
concerns and model data concerns in mind.