Add timestamps to an existing table

前端 未结 21 1142
予麋鹿
予麋鹿 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条回答
  •  半阙折子戏
    2020-12-12 15:13

    The answers before seem right however I faced issues if my table already has entries.

    I would get 'ERROR: column created_at contains null values'.

    To fix, I used:

    def up
      add_column :projects, :created_at, :datetime, default: nil, null: false
      add_column :projects, :updated_at, :datetime, default: nil, null: false
    end
    

    I then used the gem migration_data to add the time for current projects on the migration such as:

    def data
      Project.update_all created_at: Time.now
    end
    

    Then all projects created after this migration will be correctly updated. Make sure the server is restarted too so that Rails ActiveRecord starts tracking the timestamps on the record.

提交回复
热议问题