Rails4 迁移-将 null: false 添加到 add_reference 方法?

Rails4 migration- adding null: false to an add_reference method?

我刚刚开始学习 rails 很抱歉,如果这个问题的答案很明显。

我已经在我的应用程序中添加了帖子和类别 table 的迁移,现在正在使用以下行在我的帖子 table 中添加对类别的引用,默认值不为空:

add_reference :posts, :category, index: true, foreign_key: true, null: false

但是我在 运行 迁移时遇到以下错误:

SQLite3::SQLException: Cannot add a NOT NULL column with default value NULL: ALTER TABLE "posts" ADD "category_id" integer NOT NULL

我已经尝试通读 api,但无法弄清楚我做错了什么。

该消息基本上是说您不能在未定义默认值的情况下创建 "not null" 列。

我认为你应该删除 null: false 选项。

为防止 NULL 值出现在 POSTS table,添加

validates :category, presence: true

到您的 Post 模型。

另请参阅 另请检查此 post https://robots.thoughtbot.com/referential-integrity-with-foreign-keys 以更好地理解 Rails.

中的外键

也许 sqlite3 不允许这样做, 尝试

add_reference :posts, :category, index: true, foreign_key: true, null: false
change_column :posts, :category_id, :integer, null: false

进一步阅读后,这似乎是 sqlite3 的一个错误。显然,在对现有 table 进行更改时,您不能像上面那样向引用添加非空值(这在 MYSQL 中有效)。但是,您可以在从头开始创建 table 时执行此操作。通过将以上行添加到我的 create_table 类别迁移中,设法让它工作。

注意:使用引用时,there is no need to specify index: true