本文介绍了Rails 3.2 + MySQL:错误:字段"created_at"没有默认值:INSERT INTO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个新迁移,其中提到了

I created a new migration, where is mentioned

...
t.timestamps

在创建的表中添加了这两列

in the created table are added these two columns

...
| created_at  | datetime   | NO (Null)  |     | NULL (Default)   |
| updated_at  | datetime   | NO (Null)  |     | NULL (Default)   |
...

当我想创建一个新项目时,我总是收到错误消息

When I want to create a new item, I always get the error message

Mysql2::Error: Field 'created_at' doesn't have a default value: INSERT INTO `table_name` (`first_col`, `second_col`) VALUES ('a', 'b')

我错过了什么吗?我将此miniapp发送给了我的一个朋友,他能够成功运行它->记录已在数据库中创建.

Am I missing something? I sent this miniapp to a friend of mine and he is able to run successfully run it -> the record is created in database.

我想念什么?

推荐答案

我刚在Mac OS上全新安装MySql时遇到了类似情况.

I just ran into something similar on a fresh install of MySql on Mac OS.

我最终将其范围缩小到默认情况下启用严格模式"的MySql的较新版本的组合,并且我的项目中有一个表,表上带有一些可疑的约束.有问题的表是在:has_and_belongs_to_many关系中使用的联接表".以某种方式使用:created_at:updated_at属性创建了对该表具有约束:null => false的表. Rails 3.2不会自动填充:habtm关系的联接表的时间戳字段.当严格模式关闭时,MySql只会使用零日期填充cols,例如0000-00-00 00:00:00.启用严格模式后,会引发异常.

I finally narrowed it down to the combination of newer versions of MySql turning on "strict mode" by default, and my project having a table with some questionable constraints on it. The table in question was the "join table" used in a :has_and_belongs_to_many relationship. Somehow that table had been created with :created_at, and :updated_at attributes that had a constraint of :null => false on them. Rails 3.2 doesn't automatically populate the timestamp fields for join tables of :habtm relationships. When strict mode is turned off MySql will just populate the cols with zeroed out dates, like 0000-00-00 00:00:00. With strict mode turned on it raises an exception.

为解决此问题,我进行了一项迁移,以使时间戳记字段为空.像这样:

To fix the issue I ran a migration to allow the timestamp fields to be null. Like this:

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

老实说,最好删除不需要的列,但是有一些特殊情况,它们实际上是手动设置的.

Honestly, it's probably better to just drop the columns if you don't need them, but we have a couple of special cases where they actually get set manually.

这篇关于Rails 3.2 + MySQL:错误:字段"created_at"没有默认值:INSERT INTO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 10:50