I need to add timestamps (created_at updated_at) to an existing table. I tried the following code but it didn't work. I have also tried other solutions I found online but they don't work either.
class AddTimestampsToUser < ActiveRecord::Migration
def change_table
add_timestamps(:users)
end
end
How can I do it?
It's
change
, notchange_table
for Rails 4.2:The answers before seem right however I faced issues if my table already has entries.
I would get 'ERROR: column
created_at
containsnull
values'.To fix, I used:
I then used the gem migration_data to add the time for current projects on the migration such as:
Then all projects created after this migration will be correctly updated. Make sure the server is restarted too so that Rails
ActiveRecord
starts tracking the timestamps on the record.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.
not sure when exactly this was introduced, but in rails 5.2.1 you can do this:
for more see "using the change method" in the active record migrations docs.
Adds timestamps (created_at and updated_at) columns to table_name. Additional options (like null: false) are forwarded to #add_column.
Nick Davies answer is the most complete in terms of adding timestamp columns to a table with existing data. Its only downside is that it will raise
ActiveRecord::IrreversibleMigration
on adb:rollback
.It should be modified like so to work in both directions: