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?
@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:
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.Migrations are just two class methods (or instance methods in 3.1):
up
anddown
(and sometimes achange
instance method in 3.1). You want your changes to go into theup
method:If you're in 3.1 then you could also use
change
(thanks Dave):Perhaps you're confusing
def change
,def change_table
, andchange_table
.See the migration guide for further details.
The timestamp helper is only available in the
create_table
block. You can add these columns by specifying the column types manually:While this does not have the same terse syntax as the
add_timestamps
method you have specified above, Rails will still treat these columns as timestamp columns, and update the values normally.Available transformations are
http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Table.html
I personally used the following, and it updated all previous records with the current time/date: