61

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

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

3 Answers 3

197

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

belongs_to :author, optional: true

This is the corresponding 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

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'

You may also need to update any migration: change null: false to true and run rake db:redo if it had already run.

0
19

Adding optional: true along with belongs_to :author in article model will do the job.

3
  • 1
    This works only for mongoid... just ran into the same problem but using pg. Doesn't work, unfortunately.
    – Boenne
    Apr 26, 2020 at 18:37
  • 2
    The above line is directly taken from my app that runs on PG. I haven't faced any such problem while working on Postgres. Oct 19, 2020 at 7:19
  • 1
    Confirm @RajanVerma-Aarvy is correct; this worked for me on postgres db. Aug 11, 2021 at 22:55
10

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?

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, if in your original migration of articles, author_id is null, then you can have foreign key that's nullable.

2
  • 1
    I believe this is accurate for Rails 4 and below, is that correct?
    – karns
    Aug 4, 2020 at 18:21
  • @karns exactly.
    – maicher
    Oct 26, 2022 at 4:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.