我创建了一个新的迁移,其中提到
...
t.timestamps在创建的表中添加了以下两列
...
| created_at | datetime | NO (Null) | | NULL (Default) |
| updated_at | datetime | NO (Null) | | NULL (Default) |
...当我想要创建一个新项目时,我总是收到错误消息
Mysql2::Error: Field 'created_at' doesn't have a default value: INSERT INTO `table_name` (`first_col`, `second_col`) VALUES ('a', 'b')我是不是遗漏了什么?我把这个迷你应用程序发送给我的一个朋友,他能够成功地运行它,运行它->的记录是在数据库中创建的。
我遗漏了什么?
发布于 2013-05-14 04:14:20
我刚在Mac上全新安装MySql时遇到了类似的情况。
我最终将其范围缩小到在默认情况下打开“严格模式”的较新版本的MySql的组合,并且我的项目有一个表,其中包含一些可疑的约束。所讨论的表是在:has_and_belongs_to_many关系中使用的“连接表”。不知何故,该表是使用:created_at和:updated_at属性创建的,这些属性具有:null => false约束。Rails 3.2不会自动填充:habtm关系的连接表的时间戳字段。当严格模式关闭时,像0000-00-00 00:00:00一样,MySql只会用置零的日期填充cols。在开启严格模式的情况下,它会引发异常。
为了解决这个问题,我运行了一个迁移,允许时间戳字段为空。如下所示:
class ChangeNullableForTimestampsOnThing1sThing2s < ActiveRecord::Migration
def up
change_column(:thing1s_thing2s, :created_at, :datetime, :null => true)
change_column(:thing1s_thing2s, :updated_at, :datetime, :null => true)
end
def down
change_column(:thing1s_thing2s, :created_at, :datetime, :null => false)
change_column(:thing1s_thing2s, :updated_at, :datetime, :null => false)
end
end老实说,如果不需要列,最好直接删除它们,但我们有几个特殊情况,它们实际上是手动设置的。
发布于 2015-11-07 03:19:42
为了补充Jeremy的答案,在mac上,您可以使用以下命令删除严格模式
> vi /usr/local/opt/mysql/my.cnf然后替换
sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"使用
sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"https://stackoverflow.com/questions/16199710
复制相似问题