views:

139

answers:

1

I'd like to override the typecasting that ActiveRecord is doing to my datetime fields when using a finder like .first or .all but it doesn't seem to be working the way I thought it would.. I was expecting the override to return the datetime_before_type_cast like it works when I access the field directly in the bottom example.

In my model I have what I thought would override the attribute:

def datetime
  self.datetime_before_type_cast
end

SomeModel.first
#<SomeModel datetime: "2010-01-20 12:00:00"> #shouldn't it be "2010-01-20 12:00:00.123"?

SomeModel.first.datetime 
"2010-01-20 12:00:00.123"
A: 

Here's one way I found to accomplish what I was trying to do, although it seems like there must be a more direct way.

Also, I should add that the data is being rendered to xml in my controller so this seems to fit nicely with that.

def datetime
  self.datetime_before_type_cast # => 2010-01-20 12:00:00.123
end

#override to_xml, excluding the datetime field and replacing with the method of the same name
def to_xml(options = {})
  super(:methods => [:datetime], :except => :datetime)
end

SomeModel.first.to_xml

<?xml version="1.0" encoding="UTF-8"?>
...
<datetime>2010-01-20 12:00:00.123</datetime>
...
revgum