开发者

Override type casting for ActiveRecord finder

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开发者_JAVA百科_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"


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>
...


Below assumes Rails 3.x.

Remember that

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

and

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

will show different output within the Rails console because the console will call #inspect on the result of a statement.

>> SomeModel.first

will actually display

>> SomeModel.first.inspect

which internally calls #attribute_for_inspect(name) (as opposed to calling your overridden #datetime method), whereas

>> SomeModel.first.datetime 

will call the overridden #datetime method, the result of which will then have #inspect called on it.

Also, make sure you are working with a Ruby DateTime, rather than a Time, Date, or other date/time class if you wish to override the #inspect or #to_s methods to change the text format of your 'datetime' field.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜