Ruby-on-rails 在 Rails 中添加可为空的外键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27589399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:00:52  来源:igfitidea点击:

Add nullable foreign key in Rails

ruby-on-railsrubyruby-on-rails-4rails-activerecordruby-on-rails-4.2

提问by maicher

Referencing to Rails 4.2 add_foreign_keysupport:

参考 Rails 4.2 add_foreign_key支持:

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

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

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

采纳答案by user1322092

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

指南中没有任何内容暗示add_foreign_key会使相应的外部字段“NOT NULL”或必需。add_foreign_key只是添加字段是否需要与否(在你的情况下,外键约束author_idarticles)。

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

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

Here's the SQL that it would generate:

这是它将生成的 SQL:

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

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

因此,如果在您的原始迁移中articles,author_id为空,那么您可以拥有可以为空的外键。

回答by Matthias Winkelmann

Note that in Rails 5and in Rails 6you may need to mark the corresponding association as optional if it's 1:n (belongs_to), as the default was changed:

请注意,在 Rails 5Rails 6中,如果它是 1:n ( belongs_to),您可能需要将相应的关联标记为可选,因为默认值已更改:

belongs_to :author, optional: true

belongs_to :author, optional: true

This is the corresponding Changeset.

这是相应的Changeset

To use the old behavior across your application, you can also set:

要在您的应用程序中使用旧行为,您还可以设置:

Rails.application.config.active_record.belongs_to_required_by_default = false

in config/initializers/new_framework_defaults.rb

config/initializers/new_framework_defaults.rb

The error you will usually see is:

您通常会看到的错误是:

ActiveRecord::RecordInvalid: Validation failed: Class must exist
    from /usr/local/lib/ruby/gems/2.3.0/gems/activerecord-5.0.0.1/lib/active_record/validations.rb:78:in `raise_validation_error'

回答by Aarvy

Adding optional: truealong with belongs_to :authorin articlemodel will do the job.

optional: truebelongs_to :authorinarticle模型一起添加将完成这项工作。