【发布时间】:2019-05-17 04:53:42
【问题描述】:
我有一些属性需要有默认值。我已将迁移设置为在数据库中设置默认值,如下所示:
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
直接添加到数据库时,默认值效果很好。但是,如果我在 Rails 中构建一个新模型,一个属性会按预期工作,而另一个则不会:
post = Post.new
post.post_type # draft (as expected)
post.date_time # nil (expecting the current date and time)
这种行为是故意的吗?我是否也必须在模型中设置默认值?为什么Post#post_type 有效,而Post#date_time 无效?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-5 rails-activerecord