在 Rails 中添加可为空的外键 [英] Add nullable foreign key in Rails

查看:41
本文介绍了在 Rails 中添加可为空的外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考 Rails 4.2 add_foreign_key 支持:

Referencing to Rails 4.2 add_foreign_key support:

    # add a foreign key to `articles.author_id` referencing `authors.id`
    add_foreign_key :articles, :authors

如何创建可为空的外键约束,以允许 articles.author_id 有时可以为空的情况?

How to create a nullable foreign key constraint, to allow the situation, where articles.author_id can be sometimes null?

推荐答案

指南中没有任何内容暗示 add_foreign_key 会使相应的外部字段NOT NULL"或必需.add_foreign_key 只需添加一个外键约束,无论该​​字段是否需要(在您的情况下,articles 中的 author_id).

There is nothing in the guide that implies add_foreign_key would make the corresponding foreign field "NOT NULL" or required. add_foreign_key simply adds a foreign key constraint whether the field is required or not (in your case author_id in articles).

您在迁移中尝试此操作时是否遇到错误?

Did you get an error when you tried this in your migration?

这是它将生成的 SQL:

Here's the SQL that it would generate:

ALTER TABLE "articles" ADD CONSTRAINT articles_author_id_fk FOREIGN KEY ("author_id") REFERENCES "authors" ("id")

SO,如果在您对 articles 的原始迁移中,author_id 为空,那么您可以拥有可以为空的外键.

SO, if in your original migration of articles, author_id is null, then you can have foreign key that's nullable.

这篇关于在 Rails 中添加可为空的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆