不久前,我们将应用程序升级到 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
我们应用程序的重要部分是:
- ruby '1.9.3', :engine => 'jruby', :engine_version => '1.7.9'
- gem 'rails', '4.0.2'
- gem 'activerecord-jdbcpostgresql-adapter', '1.3.4'
- postgresql:9.3.1 稳定
您是否知道可能导致问题的原因以及我们如何将默认生成改回NOT NULL?
最佳答案
我不知道除the source 以外的其他地方是否有记录表示您可以将常用的列选项传递给 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
所以你可以说:
create_table :model do |t|
#...
t.timestamps :null => false
end
并且您的列应该为 NOT NULL。
如果您查看 3.2 version ,你会看到发生了什么:
def timestamps(*args)
options = { :null => false }.merge(args.extract_options!)
#...
end
所以 3.2 默认将时间戳列创建为 NOT NULL,但 4.0 没有。
关于ruby-on-rails - Rails 迁移生成默认时间戳(created_at、updated_at)为 NULLABLE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20956526/