How to set a default value for a datetime column to record creation time in a migration?

后端 未结 7 684
日久生厌
日久生厌 2020-12-04 13:42

Consider the table creation script below:

create_table :foo do |t|
  t.datetime :starts_at, :null => false
end

Is it\'s possible to set

7条回答
  •  执念已碎
    2020-12-04 14:17

    If you need to change an existing DateTime column in Rails 5 (rather than creating a new table as specified in other answers) so that it can take advantage of the default date capability, you can create a migration like this:

    class MakeStartsAtDefaultDateForFoo < ActiveRecord::Migration[5.0]
      def change
        change_column :foos, :starts_at, :datetime, default: -> { 'CURRENT_TIMESTAMP' }
      end
    end
    

提交回复
热议问题