I need to add timestamps (created_at
& updated_at
) to an existing table. I tried the following code but it didn\'t work.
class
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