Add timestamps to an existing table

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

    The issue with most of the answers here is that if you default to Time.zone.now all records will have the time that the migration was run as their default time, which is probably not what you want. In rails 5 you can instead use now(). This will set the timestamps for existing records as the time the migration was run, and as the start time of the commit transaction for newly inserted records.

    class AddTimestampsToUsers < ActiveRecord::Migration def change add_timestamps :users, default: -> { 'now()' }, null: false end end

提交回复
热议问题