Rails migration set current date as default value
You can set default date on migration from Rails 5
create_table :posts do |t|
t.datetime :published_at, default: -> { 'NOW()' }
end
Here a link from rails repo
You can pass a lambda for dynamic initializers.
create_table "test", :force => true do |t|
t.date "day", default: -> { 'CURRENT_DATE' }
end
Old answer
Rails does not support dynamic default values in migrations. Whatever is in your migration during its execution will be set at the DB level and will stay that way until the migration is rolled back, overridden, or reset. But you can easily add dynamic defaults at the model level since it's evaluated at runtime.
1) Setting default values using after_initialize
callback
class Test
def after_initialize
self.day ||= Date.today if new_record?
end
end
Use this approach only if you need to access the attribute after initialization and before saving the record. This approach has extra processing cost while loading a query result, as the block has to be executed for every result object.
2) Setting default values using before_create
callback
class Test
before_create do
self.day = Date.today unless self.day
end
end
This callback is triggered by a create
call on your model.
There are many more callbacks. For example, setting the date before validation on create
and update
.
class Test
before_validation on: [:create, :update] do
self.day = Date.today
end
end
3) Using the default_value_for gem
class Test
default_value_for :day do
Date.today
end
end