I need to add timestamps (created_at
& updated_at
) to an existing table. I tried the following code but it didn\'t work.
class
For those who don't use Rails but do use activerecord, the following also adds a column to an existing model, example is for an integer field.
ActiveRecord::Schema.define do
change_table 'MYTABLE' do |table|
add_column(:mytable, :my_field_name, :integer)
end
end
@user1899434's response picked up on the fact that an "existing" table here could mean a table with records already in it, records that you might not want to drop. So when you add timestamps with null: false, which is the default and often desirable, those existing records are all invalid.
But I think that answer can be improved upon, by combining the two steps into one migration, as well as using the more semantic add_timestamps method:
def change
add_timestamps :projects, default: Time.zone.now
change_column_default :projects, :created_at, nil
change_column_default :projects, :updated_at, nil
end
You could substitute some other timestamp for DateTime.now
, like if you wanted preexisting records to be created/updated at the dawn of time instead.
I personally used the following, and it updated all previous records with the current time/date:
add_column :<table>, :created_at, :datetime, default: Time.zone.now, null: false
add_column :<table>, :updated_at, :datetime, default: Time.zone.now, null: false