I have some attributes that need to have default values. I've set up my migrations to set the defaults in the database as follows:
class AddDefaultsToModel < ActiveRecord::Migration[5.2]
def change
change_column :posts, :post_type, :string, default: 'draft'
change_column :posts, :date_time, :datetime, default: -> { 'CURRENT_TIMESTAMP' }
end
end
The defaults work great when adding directly to the database. However, if I build a new model in Rails, one attribute works as expected, the other doesn't:
post = Post.new
post.post_type # draft (as expected)
post.date_time # nil (expecting the current date and time)
Is this behavior deliberate? Do I have to set the default in the model as well? Why does Post#post_type
work but not Post#date_time
?