Add timestamps to an existing table

前端 未结 21 1146
予麋鹿
予麋鹿 2020-12-12 14:34

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

class          


        
21条回答
  •  旧时难觅i
    2020-12-12 15:16

    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 a db:rollback.

    It should be modified like so to work in both directions:

    def change
      add_timestamps :campaigns, default: DateTime.now
      change_column_default :campaigns, :created_at, from: DateTime.now, to: nil
      change_column_default :campaigns, :updated_at, from: DateTime.now, to: nil
    end
    

提交回复
热议问题