Add timestamps to an existing table

前端 未结 21 1143
予麋鹿
予麋鹿 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:26

    @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:

    def change
      add_timestamps :projects, default: Time.zone.now
      change_column_default :projects, :created_at, nil
      change_column_default :projects, :updated_at, nil
    end
    

    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.

提交回复
热议问题