我创建了一个全新的 Rails 应用程序,生成一些脚手架和一些模型。经过几次测试后,我意识到 t.timestamps 生成的列不包含“传统”:null => false 选项。我需要这种行为,我看不出这是做什么的。
我重新创建了一个新应用程序,认为这是 Rails 4 的新功能,但我无法获得保存行为。在此应用程序中,时间戳按其应有的方式工作。
当我创建帖子时,在 Rails 控制台的“调试应用程序”中,我们可以看到:
Loading development environment (Rails 4.0.1)
2.0.0-p247 :001 > Post.create(title:"test")
(0.1ms) begin transaction SQL (8.6ms) INSERT INTO "posts" ("created_at", "title", "updated_at") VALUES (?, ?, ?) [["created_at", Wed, 27 Nov 2013 21:19:01 EST -05:00], ["title", "test"], ["updated_at", Wed, 27 Nov 2013 21:19:01 EST -05:00]]
(0.8ms) commit transaction
=> #<Post id: 1, title: "test", content: nil, excerpt: nil, dashboard: nil, created_at: "2013-11-28 02:19:01", updated_at: "2013-11-28 02:19:01">
2.0.0-p247 :002 > Post.last
Post Load (0.4ms) SELECT "posts".* FROM "posts" ORDER BY "posts"."id" DESC LIMIT 1
=> #<Post id: 1, title: "test", content: nil, excerpt: nil, dashboard: nil, created_at: nil, updated_at: nil>
时间戳已设置但未保存在数据库中。
我想我错过了一些东西。知道如何恢复默认行为吗?
编辑:迁移文件
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :title
t.text :content
t.text :excerpt
t.boolean :dashboard
t.timestamps
end
end
end