Ruby on rails 在Mongoid中,Date、Time、DateTime和TimeWithZone字段类型是否存在任何差异?
文档中提到了四种与时间相关的字段类型()。在其他数据库中,我可以看到这些字段将如何成为数据库中的不同类型,但对于MongoDB,它们不都是日期类型吗?这只是为了与ActiveRecord保持一致吗?它们之间几乎没有区别,都是包装时间类型。 从mongo取消序列化后,您可以更改DateTime、Date或TimeWithZone以获取此类型的实例 Mongoid扩展了此类以添加数据绑定的demongoize/mongoize方法。因此,唯一的区别在于实施 所以,时间的实施Ruby on rails 在Mongoid中,Date、Time、DateTime和TimeWithZone字段类型是否存在任何差异?,ruby-on-rails,mongodb,Ruby On Rails,Mongodb,文档中提到了四种与时间相关的字段类型()。在其他数据库中,我可以看到这些字段将如何成为数据库中的不同类型,但对于MongoDB,它们不都是日期类型吗?这只是为了与ActiveRecord保持一致吗?它们之间几乎没有区别,都是包装时间类型。 从mongo取消序列化后,您可以更改DateTime、Date或TimeWithZone以获取此类型的实例 Mongoid扩展了此类以添加数据绑定的demongoize/mongoize方法。因此,唯一的区别在于实施 所以,时间的实施 def demongoi
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
实施日期
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
您可以检查其他含义
只是一个警告:我在rspec测试中发现了一个奇怪的错误,在这个错误中,对DateTime字段的断言有时会因为毫秒差而失败。对于时间类型,或者在断言之前系统地重新加载对象时,我没有这个问题。这个答案在Mongoid 6.2中是不正确的。Mongoid的
Time
数据类型用于存储ActiveSupport::TimeWithZone
,而DateTime
是纯RubyDateTime
。这两者之间有着重要的区别。