为什么我可以 运行 在 seeds.rb 中但不能在我的控制器中创建具有未定义多态关联的模型?

Why can I run create on model with undefined polymorphic association in seeds.rb but not in my controller?

我 运行 我的 seeds.rb 文件中的以下代码。

page = BlocksEditor::Page.create(name: "A Page")

当我尝试 运行 控制器中的相同代码时。我收到一个验证错误,说多态关联是空的,这是真的。我注销了 page 而 运行 种子和类型和 ID 字段如预期的那样为空。 page.valid? returns 正确。

为什么种子文件验证不通过?更好的是,我如何定义可选的多态关联?我知道我想要这些字段,但我知道它们有时不会被填充。

显然,Rails 5 makes the belongs_to association mandatory。使用 optional: true 使其可选。我仍然不知道为什么种子文件给出的行为与控制器不同,但这解决了问题。