I need to add timestamps (created_at
& updated_at
) to an existing table. I tried the following code but it didn\'t work.
class
add_timestamps(table_name, options = {}) public
Adds timestamps (created_at and updated_at) columns to table_name. Additional options (like null: false) are forwarded to #add_column.
class AddTimestampsToUsers < ActiveRecord::Migration
def change
add_timestamps(:users, null: false)
end
end
A lot of answers here, but I'll post mine too because none of the previous ones really worked for me :)
As some have noted, #add_timestamps
unfortunately adds the null: false
restriction, which will cause old rows to be invalid because they don't have these values populated. Most answers here suggest that we set some default value (Time.zone.now
), but I wouldn't like to do that because these default timestamps for old data will not be correct. I don't see the value in adding incorrect data to the table.
So my migration was simply:
class AddTimestampsToUser < ActiveRecord::Migration
def change_table
add_column :projects, :created_at, :datetime
add_column :projects, :updated_at, :datetime
end
end
No null: false
, no other restrictions. Old rows will continue being valid with created_at
as NULL
, and update_at
as NULL
(until some update is performed to the row). New rows will have created_at
and updated_at
populated as expected.
I ran into the same issue on Rails 5 trying to use
change_table :my_table do |t|
t.timestamps
end
I was able to add the timestamp columns manually with the following:
change_table :my_table do |t|
t.datetime :created_at, null: false, default: DateTime.now
t.datetime :updated_at, null: false, default: DateTime.now
end
It's change
, not change_table
for Rails 4.2:
class AddTimestampsToUsers < ActiveRecord::Migration
def change
add_timestamps(:users)
end
end
The issue with most of the answers here is that if you default to Time.zone.now
all records will have the time that the migration was run as their default time, which is probably not what you want. In rails 5 you can instead use now()
. This will set the timestamps for existing records as the time the migration was run, and as the start time of the commit transaction for newly inserted records.
class AddTimestampsToUsers < ActiveRecord::Migration
def change
add_timestamps :users, default: -> { 'now()' }, null: false
end
end
def change
add_timestamps :table_name
end