Add timestamps to an existing table

leonel picture leonel · Sep 25, 2011 · Viewed 91.7k times · Source

I need to add timestamps (created_at & updated_at) to an existing table. I tried the following code but it didn't work.

class AddTimestampsToUser < ActiveRecord::Migration
    def change_table
        add_timestamps(:users)
    end
end

Answer

Ben Simpson picture Ben Simpson · Sep 25, 2011

The timestamp helper is only available in the create_table block. You can add these columns by specifying the column types manually:

class AddTimestampsToUser < ActiveRecord::Migration
  def change_table
    add_column :users, :created_at, :datetime, null: false
    add_column :users, :updated_at, :datetime, null: false
  end
end

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.