views:

1437

answers:

2

I am having a problem with ActiveRecord inserting the DATETIME as per the documentation; "Active Record automatically timestamps create and update operations if the table has fields named created_at/created_on or updated_at/updated_on." I have a column named created_at but ActiveRecord is not inserting the DATETIME. My insert query looks as follows:

def add_record(server_id, backup_type)
  Record.create(:server_id => server_id, :backup_type => backup_type)
end

I know I could insert the time using something like

:created_at => "#{Time.now.strftime("%Y-%m-%d %H:%M:%S")}"

The reason that I want to stay away from that is due to differences in time between the servers, both locally and geographically. I am wondering if there is a way to run the type in the same create method, such as:

def add_record(server_id, backup_type)
  Record.create(:server_id => server_id, :backup_type => backup_type, created_at => DATETIME())
end

Thank you.

A: 

If the created_at field type is TimeStamp then you can use the function CURRENT_TIMESTAMP() to set the value of the field.

Noah Goodrich
+2  A: 

You have a created_at column, but ActiveRecord is not creating a timestamp? What's the column type of your created_at column? Perhaps you could show us your migration?

Also, if you tell Rails to use UTC (default in 2.2, I think), the time values will be correct, regardless of different server locales.

And, lastly: You can just pass a time/date/datetime instance, you don't have to format it yourself. E.g. YourModel.create(:a_time_column => Time.now)

August Lilleaas
for some reason i was doing CallLog.callstart = Date.new. that set the value to 0000-00-00 00:00:00. based on this answer, I changed it to CallLog.callstart = Time.now and I am feeling much better now.
kinjal