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

Viewed 101516

Consider the table creation script below:

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

Is it's possible to set the default value as the current time?

I am trying to find a DB independent equivalent in rails for the SQL column definitions given below:

Oracle Syntax

start_at DATE DEFAULT SYSDATE() 

MySQL Syntax

start_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

OR

start_at DATETIME DEFAULT NOW()
8 Answers

Did you know that upserts fail unless you have a default updated_at/created_at????

there is no migration flag which automatically does this, you have to manually include an options object with a default key

create_table :table_foos do |t|
  #...
  # date with timestamp
  t.datetime :last_something_at, null: false, default: -> { "CURRENT_TIMESTAMP" }
  
  # standard timestamps
  t.timestamps({default: -> { "CURRENT_TIMESTAMP" }})
end
Related