Add timestamps to an existing table

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

    For those who don't use Rails but do use activerecord, the following also adds a column to an existing model, example is for an integer field.

    ActiveRecord::Schema.define do
      change_table 'MYTABLE' do |table|
        add_column(:mytable, :my_field_name, :integer)
      end
    end
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-12 15:26

    I personally used the following, and it updated all previous records with the current time/date:

    add_column :<table>, :created_at, :datetime, default: Time.zone.now, null: false
    add_column :<table>, :updated_at, :datetime, default: Time.zone.now, null: false
    
    0 讨论(0)
提交回复
热议问题