Rails迁移生成默认时间戳(created_at,updated_at)为NULLABLE

mae*_*bow 11 migration postgresql activerecord ruby-on-rails jruby

前段时间我们将应用程序升级到Rails 4并切换到JRuby.

在此更改之前,迁移会将默认时间戳创建为NOT NULL.在更改之后,缺少NOT NULL.

我们创建这些时间戳(created_at,updated_at)如下:

class Model < ActiveRecord::Migration
  def change
    create_table :model do |t|
      t.belongs_to :user, :null => false

      t.text :content

      t.timestamps
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

我们的应用程序的重要部分是:

  • ruby'1.9.3',:engine =>'jruby',:engine_version =>'1.7.9'
  • 宝石'轨道','4.0.2'
  • gem'activerecord -jdbcpostgresql-adapter','1.3.4'
  • postgresql:稳定9.3.1

您是否知道可能导致问题的原因以及我们如何将默认生成更改回NOT NULL

mu *_*ort 7

我不知道它是否记录在任何地方,但指示您可以将通常的列选项传递给t.timestamps:

# Appends <tt>:datetime</tt> columns <tt>:created_at</tt> and
# <tt>:updated_at</tt> to the table.
def timestamps(*args)
  options = args.extract_options!
  column(:created_at, :datetime, options)
  column(:updated_at, :datetime, options)
end
Run Code Online (Sandbox Code Playgroud)

所以你可以说:

create_table :model do |t|
  #...
  t.timestamps :null => false
end
Run Code Online (Sandbox Code Playgroud)

并且您的列应该是NOT NULL.

如果你看看3.2版本,你会看到发生了什么:

def timestamps(*args)
  options = { :null => false }.merge(args.extract_options!)
  #...
end
Run Code Online (Sandbox Code Playgroud)

所以3.2默认情况下将timestamp列创建为NOT NULL,但4.0不会.

  • FWIW,看起来时间戳默认为"null:false"只在3.2行中为真.它被添加到[rails/rails#3334](https://github.com/rails/rails/pull/3334)然后[reverted](https://github.com/rails/rails/commit/fcef728)超过4.0. (3认同)