Search code examples
ruby-on-railsrubyrails-activerecordrails-migrations

Add timestamps to an existing table


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

Solution

  • 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.