2010-02-04 27 views
1

我想重写ActiveRecord在使用类似.first或.all的查找器时对我的日期时间字段进行的类型转换,但它似乎没有像我认为的那样工作..我期待覆盖返回datetime_before_type_cast就像它在我直接访问底部的例子中的字段时工作。ActiveRecord查找器的替代类型转换

在我的模型我有什么,我以为会覆盖属性:

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" 
+0

你想在这里产生什么结果? – tadman 2010-02-04 17:23:54

+0

更新了问题以增加我的目标。 – revgum 2010-02-04 18:22:25

+0

看起来Rails 3的主动支持可能对datetime问题有一些相关的变化:http://guides.rails.info/3_0_release_notes.html#active-support – 2010-02-05 21:23:05

回答

0

这是我发现要完成什么,我试图做一个标准,尽管它看起来必须有一个更直接的方式。

此外,我应该补充说,数据正在呈现给我的控制器中的XML,所以这似乎很适合。

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

以下假设的Rails 3.x的

记住

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

将显示Rails的控制台中不同的输出,因为控制台将调用#inspect在语句的结果。

>> SomeModel.first 

将实际显示

>> SomeModel.first.inspect 

其内部调用#attribute_for_inspect(名称)(而不是调用你重写#datetime方法),而

>> SomeModel.first.datetime 

将调用重写# datetime方法,其结果将调用#inspect。

此外,如果您希望重写#inspect或#to_s方法来更改'datetime的文本格式,请确保您正在使用Ruby DateTime,而不是Time,Date或其他日期/时间类'字段。