在 Rails 应用程序中,我有以下形式的模型代码:
def do_stuff(resource)
models = Model.where(resource: resource)
operated_at = DateTime.now
models.each { |model| some_operation(model, operated_at) }
some_other_operation models, operated_at
end
def some_operation(model, operated_at)
model.date_time_field = operated_at
model.save
end
def some_other_operation(models, operated_at)
models.each do |model|
if model.date_time_field < operated_at
# do something
end
end
end
在这种情况下,将始终执行 some_other_operation 的“做某事”块。更奇怪的是,如果我在控制台中设置它而没有所有定义的功能,则比较会按预期工作。例子:
> model = Model.first
> time_var = DateTime.now
> model.last_imported_at = time_var
=> Fri, 25 Oct 2013 21:14:06 +0000
> model.save
=> true
> model.last_imported_at < time_var
=> false
> model.last_imported_at == time_var
=> true
最后,如果,some_other_operation
我改为通过以下方式进行比较:
if model.date_time_field.to_i < operated_at.to_i
# do something
end
仅在预期时才到达“做某事”块。我怀疑这是因为该to_i
方法将丢弃在 DateTime 对象上定义的几分之一秒,并且该operated_at
变量实际上被重新定义DateTime.now
为每个方法的范围。如果是这种情况,那么我想我的问题是如何强制operated_at
不为每个范围重新定义?