小编Dow*_*ker的帖子

使用 CURRENT_TIMESTAMP 的 Rails 5.2 和 Active Record 迁移

我有一些属性需要有默认值。我已经设置了迁移以在数据库中设置默认值,如下所示:

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
Run Code Online (Sandbox Code Playgroud)

直接添加到数据库时,默认值效果很好。但是,如果我在 Rails 中构建一个新模型,一个属性会按预期工作,而另一个则不会:

post = Post.new
post.post_type # draft (as expected)
post.date_time # nil (expecting the current date and time)
Run Code Online (Sandbox Code Playgroud)

这种行为是故意的吗?我是否也必须在模型中设置默认值?为什么Post#post_type有效但无效Post#date_time

ruby-on-rails rails-activerecord ruby-on-rails-5

5
推荐指数
1
解决办法
1957
查看次数