Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timestamp not updating in RoR application

I have a small site that sorts news topics by date of submission to the second. Locally, this works fine. Even when rapidly posting stories in a row there is a difference in the time stamp.

Example:

Submitted Fri Mar 25 14:31:09 2011
Submitted Fri Mar 25 14:30:45 2011
Submitted Fri Mar 25 14:30:23 2011

However, once the code is pushed to heroku and the database is set up with MongoHQ the seconds value seems ignored or frozen.

Example Document DateTime value:

added_on 03/14/2011 09:58 AM

Example timestamps:

Submitted Thu Mar 24 13:48:40 2011
Submitted Thu Mar 24 13:48:40 2011
Submitted Thu Mar 24 13:48:40 2011
Submitted Thu Mar 24 13:48:40 2011

It appears the seconds value isn't updating?

Here is the model code,

class Post
  include Mongoid::Document
  field :link
  field :title
  field :synopsis
  field :added_on, :type => DateTime, :default => DateTime.now
  field :poster
  field :category

  validates_presence_of :link
  validates_presence_of :title
  validates_presence_of :synopsis
  validates_presence_of :category

  validates_uniqueness_of :link
  validates_uniqueness_of :title

  embeds_many :replies

  #referenced_in :topic
end
like image 926
moctopus Avatar asked Dec 22 '22 16:12

moctopus


2 Answers

My guess would be that you need to change the default value into a Proc.

In development mode, your models are being reloaded every request, so DateTime.now is always current. In production, however, the class is only loaded once (per dyno) during app startup, and DateTime.now results in a static value.

field :added_on, :type => DateTime, :default => Proc.new { DateTime.now }

should be what you want.

like image 106
Michelle Tilley Avatar answered Dec 28 '22 06:12

Michelle Tilley


This declaration in your class:

field :added_on, :type => DateTime, :default => DateTime.now

Will be handled when the file is read. On Heroku, this happens when you push your update and the slug is compiled. The result is that the default value is fixed at whatever the time happens to be when the slug is compiled. Try this instead:

field :added_on, :type => DateTime, :default => lambda { DateTime.now }

Everything probably works fine in your development environment because the file keeps getting reloaded all the time.

like image 35
mu is too short Avatar answered Dec 28 '22 05:12

mu is too short