文档中提到了四种与时间相关的字段类型(http://mongoid.org/en/mongoid/docs/documents.html#fields).在其他数据库中,我可以看到这些字段将如何成为数据库中的不同类型,但对于MongoDB,它们不都将是日期类型吗?这只是为了与ActiveRecord保持一致吗?
文档中提到了四种与时间相关的字段类型(http://mongoid.org/en/mongoid/docs/documents.html#fields).在其他数据库中,我可以看到这些字段将如何成为数据库中的不同类型,但对于MongoDB,它们不都将是日期类型吗?这只是为了与ActiveRecord保持一致吗?
它们之间几乎没有区别,都是包装时间类型.
Mongoid扩展了这个类,为数据绑定添加demongoize/mongoize方法.因此,唯一的区别在于实施.
所以,现在是实施的时候了
def demongoize(object)
return nil if object.blank?
object = object.getlocal unless Mongoid::Config.use_utc?
if Mongoid::Config.use_activesupport_time_zone?
object = object.in_time_zone(Mongoid.time_zone)
end
object
end
def mongoize(object)
return nil if object.blank?
begin
time = object.__mongoize_time__
if object.respond_to?(:sec_fraction)
::Time.at(time.to_i, object.sec_fraction * 10**6).utc
elsif time.respond_to?(:subsec)
::Time.at(time.to_i, time.subsec * 10**6).utc
else
::Time.at(time.to_i, time.usec).utc
end
rescue ArgumentError
EPOCH
end
end
实施日期
def demongoize(object)
::Date.new(object.year, object.month, object.day) if object
end
def mongoize(object)
unless object.blank?
begin
time = object.__mongoize_time__
::Time.utc(time.year, time.month, time.day)
rescue ArgumentError
EPOCH
end
end
end
你可以查看其他暗示
https://github.com/mongoid/mongoid/blob/master/lib/mongoid/extensions/date.rb#L46