Comparing identical DateTime objects in ruby — why are these two DateTime.now's not equal?

后端 未结 4 841
后悔当初
后悔当初 2021-01-13 12:55

In a rails app, I have model code of the form:

def do_stuff(resource)
  models = Model.where(resource: resource)
  operated_at = DateTime.now

  models.each         


        
4条回答
  •  遥遥无期
    2021-01-13 13:29

    Possible clue; the act of saving and reloading truncates the seconds_fraction part of the DateTime. The date field becomes an instance of ActiveSupport::TimeWithZone. Just saving without reloading doesn't do this; the real DateTime object is still there.

    2.0.0-p195 :001 > dt            =  DateTest.create
    2.0.0-p195 :002 > right_now     =  DateTime.now
    2.0.0-p195 :004 > dt.created_at =  right_now
    2.0.0-p195 :005 > dt.created_at == right_now
     => true 
    
    2.0.0-p195 :006 > dt.save
    2.0.0-p195 :007 > dt.created_at == right_now
     => true 
    
    2.0.0-p195 :008 > dt = DateTest.find(dt.id)
    2.0.0-p195 :009 > dt.created_at == right_now
     => false 
    

    Edit: of course calling models.each is going to load the models there and then because of the lazy loading behaviour. Props to the other answerer. As an experiment, try setting models to Model.where(resource: resource).to_a.

提交回复
热议问题