XML序列化不包括Rails的模型,日期时间字段毫秒 [英] XML Serialization is not including milliseconds in datetime field from Rails model

查看:171
本文介绍了XML序列化不包括Rails的模型,日期时间字段毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在默认情况下,从数据库中的时间字段被转换并剥离毫秒:

By default, the datetime field from the database is being converted and stripping off the milliseconds:

some_datetime =>2009-11-11T02:19:36Z

some_datetime => "2009-11-11T02:19:36Z"

attribute_before_type_cast('some_datetime')=>2009-11-11 02:19:36.145

attribute_before_type_cast('some_datetime') => "2009-11-11 02:19:36.145"

如果我尝试overrride的访问此属性等等;

If I try to overrride the accessor for this attribute like;

def some_datetime
  attribute_before_type_cast('some_datetime')
end

当我尝试to_xml为模式,我得到以下错误:

when I try "to_xml" for that model, I get the following error:

NoMethodError(未定义的方法   `XMLSCHEMA为2009-11-11   02:19:36.145:字符串):

NoMethodError (undefined method `xmlschema' for "2009-11-11 02:19:36.145":String):

我试图解析字符串到一个Time对象,但不能得到一个包含毫秒;

I have tried to parse the String to a Time object but can't get one to include the milliseconds;

  def some_datetime
    Time.parse(attribute_before_type_cast('some_datetime').sub(/\s/,"T").sub(/$/,"Z"))
  end

谁能帮助获得获得日期时间与to_xml呈现毫秒?

Can anyone help get get a datetime with milliseconds rendered by to_xml?

推荐答案

事实证明,我可以排除原始日期时间字段,并添加自定义的方法,从而使该日期时间为一个字符串to_xml。这种感觉的hackish,但它的工作..有另一种方式来直接获得毫秒原始日期时间字段?

As it turns out, I can exclude the original datetime field, and add a custom method which in turn renders the datetime as a string to the to_xml. This feels hackish, but it's working.. Is there another way to get milliseconds directly in the original datetime field?

在每一个模型,我排除除了有,我想改变日期时间字段名称,和我有相同名称返回属性,它是类型强制转换前的方法。

In each model, I exclude "except" the field names that have datetimes that I want changed, and I include "methods" with the same name returning the attribute before it is typecasted.

  def to_xml(options = {})
    options[:methods] = [:some_datetime]
    options[:except] = [:some_datetime]
    super
  end

  def some_datetime
    attribute_before_type_cast('some_datetime')
  end

渲染to_xml是伟大的工作与模型包括与任何其他选项我通过在

Rendering to_xml is working great with models included and any other options I pass in.

这篇关于XML序列化不包括Rails的模型,日期时间字段毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆