How toAdd missing `created_at` and `updated_at` columns in Rails
If, like me, you forgot to add the t.timestamps when creating a new table, you may want to add them in the future, however, most likely you already have data there.
To add those columns you can create a new migration and run this code in the change method
add_timestamps(:table_name)
This may work if you don't have data, but if you already have rows in your table you want to add a default value, one option is do do
add_timestamps(:notifications, default: DateTime.now)
The problem with this is that you are now storing the datetime value in your databaoption thisas a fixed value, so new rows will use this fixed value, to solve this problem change it to:
add_timestamps(:notifications, default: -> { "CURRENT_TIMESTAMP" })
This way it will work correctly and for already existent row it will use the timestamp of when you run the migration.
Do you like my content?
Your sponsorship helps me create more tutorials, articles, and open-source tools.