I have a problem with overwriting accessors in a model and using the to_xml
method later on the model. The problem is, that to_xml
seems to use the default getter method, rather than using read_attribute
.
My model:
class Announcement < ActiveRecord::Base
...
def created_at
date = self[:created_at]
"#{german_date(date)} #{german_time(date)} #{I18n.t(:clock)}"
end
...
end
I'm using this, in order to easily run through parameters in my haml views, by always having the correct method for labels and text_fields. Because I need some attributes to be shown modified, I've overwritten the accessor.
-# Minified example ...
= form_for ...
- %i(a b c d e).each do |attr|
= f.label attr
= f.text_field attr
The problem is: When I run to_xml
, I get this problem:
NoMethodError: undefined method `xmlschema' for "15.03.2009 18:17 Uhr":String
Obviously, to_xml
is using my custom getter rather than read_attribute(:created_at)
, which would give the correct value. I'm astonished to not have found this problem somewhere else, but IS there a solution to this problem?
There is a way using the options and a block with to_xml
announcment.to_xml(except: :created_at, procs: -> (options, record) {
options[:builder].tag!("created-at", record.read_attribute(:created_at))
})
That's not pretty though. I would just use a decorator for your views and leave the model attribute methods alone, Draper works great with Rails 4.