如何使用 SQLite 在 Rails6 中添加引用列迁移

How to add reference column migration in Rails 6 with SQLite

在Rails6中添加参考列迁移而没有得到SQLite3::SQLException: Cannot add a NOT NULL column with default value NULL的正确方法是什么?

我可以破解它让它工作;但是,我正在为毕业生准备教程 class,所以我想确保我正在做它 "by the book"。

起点是Postclass(想想"blog post")。我想添加一个 Author class 并在作者和帖子之间建立一对多关系。添加 author class 和 运行 相应的迁移后,我创建一个迁移以添加对 Post:

Author 引用

rails g migration AddAuthorToPost author:references

此命令生成:

class AddAuthorToPost < ActiveRecord::Migration[6.0]
  def change
    add_reference :posts, :author, null: false, foreign_key: true
  end
end

当然,问题是 SQLite 会抱怨,因为它不会容忍 null 外键的可能性 --- 即使 Post table 是空的: (How to solve "Cannot add a NOT NULL column with default value NULL" in SQLite3?)

我回头看了去年的教程(由不同的导师准备),生成器没有将null: false添加到迁移中。 (另见

从迁移中删除 null: false 允许迁移到 运行;但是,"disabling safety features" 在 class 房间设置中似乎不合适 :)

有更好的方法吗?

默认情况下,需要 foreign_key(在应用程序级别,而不是在数据库级别)。

要禁用,在config/application.rb中添加

config.active_record.belongs_to_required_by_default = false

class YourModel < ApplicationRecord
  belongs_to :another_model, optional: true
end