In Rails 8.1, why does saving a Book that belongs_to :author fail with "Author must exist", and how do you allow authorless books?
answer
- required unless told otherwise
- belongs_to_required_by_default since 5.0 defaults
- optional: true opts out
- the :required message reads must exist
- 7.1 defaults: check only nil or changed key
basics
~20 sbelongs_to is required by default: Rails adds a presence validation on the association whose message is "must exist". Declare belongs_to :author, optional: true to allow a nil author, and make the author_id column nullable to match.
solid answer
~40 sSince the Rails 5.0 framework defaults, `belongs_to_required_by_default` is `true`, and a new 8.1 app inherits it through `load_defaults 8.1`. Each `belongs_to` then gets a presence validation on the association with the `:required` message, so a book without an author fails with `Author must exist`; `save` returns `false` and `save!` raises `ActiveRecord::RecordInvalid`. Adding `optional: true` removes that validation; the column must also allow `NULL` or the database rejects the row. `validate: false` does not turn it off. Since the 7.1 defaults the check runs only when `author_id` is nil or changed, so unrelated updates no longer load the author just to validate. It is an application check, not a foreign key constraint.
code
ruby · 11 linesclass Book < ApplicationRecord
belongs_to :author # required: adds the "must exist" check
belongs_to :donor, optional: true # may be nil (column must allow NULL)
end
book = Book.new(title: "Anonymous pamphlet")
book.save # => false
book.errors.full_messages # => ["Author must exist"]
book.author = Author.find_by!(name: "Unknown")
book.save # => true (donor may stay nil)go deeper
Recall that belongs_to is required by default, that the error reads "must exist", and that optional: true is the switch to allow a missing parent.
Explain that the check validates the association, how load_defaults sets it, and why the 7.1 defaults only validate a nil or changed key.
Separate validation from integrity: a Rails check can race and be bypassed, so pair required associations with database constraints and keep nullability consistent.
Use framework-default upgrades deliberately: flags like this one change behaviour app-wide, so stage them through load_defaults and fix the fallout in tests first.
## Where "must exist" comes from In a Rails 8.1 app every `belongs_to` is **required by default**. When you declare ```ruby class Book < ApplicationRecord belongs_to :author end ``` Active Record adds a presence validation on the `author` association, using the `:required` error message, whose English text is **"must exist"**. Saving a book whose author is missing therefore fails validation: `save` returns `false`, `save!` raises `ActiveRecord::RecordInvalid`, and `book.errors.full_messages` contains `"Author must exist"`. The switch behind this is `config.active_record.belongs_to_required_by_default`. It became `true` in the Rails 5.0 framework defaults, and a new app gets it through `config.load_defaults 8.1`, which includes every earlier version's defaults. An old app that never raised its `load_defaults` past 4.2 still has optional belongs_to, which is why upgrades sometimes surface a wave of "must exist" errors. ## Opting out with optional: true When a book genuinely may have no author (a used-bookstore intake of anonymous pamphlets, say), declare it: ```ruby class Book < ApplicationRecord belongs_to :author, optional: true end ``` Points worth knowing: - `optional: true` only removes the Rails validation. If the `author_id` column is `NOT NULL`, the database still rejects the row, so the migration has to agree. - The older `required: false` spelling is still accepted and translated to `optional: true`, but the API docs call `required` deprecated; write `optional:`. - `validate: false` does **not** switch the check off. On `belongs_to`, `validate:` controls whether the *associated object* is validated when the book saves; the required presence check is added separately. - `inverse_of:` and `autosave:` are unrelated: one pairs in-memory objects, the other decides whether the associated record is saved with the owner. ## What the check actually does in 8.1 The presence check validates the **association**, not just the id. That has a cost: confirming that `author` is present means loading the `Author` row. Before the 7.1 defaults, Rails did that on every save of every book, even when `author_id` had not changed. Since the 7.1 defaults, `config.active_record.belongs_to_required_validates_foreign_key` is `false`, and the check runs only when it can matter: 1. `author_id` is `nil`, or 2. `author_id` changed since the last save (or, on a polymorphic belongs_to, the type column is nil or changed). So editing a book's title no longer issues a `SELECT` on `authors` just to validate. When the key *is* new or changed, Rails reads the association; if the id points at no row, the reader returns `nil` and the book gets "Author must exist". If the author object is already loaded (for example because you assigned `book.author = author`), no query is needed. | Situation on save | Load defaults 8.1 behaviour | |---|---| | `author_id` unchanged | check skipped, no query | | `author_id` nil | fails with "must exist" | | `author_id` changed to an existing id | author loaded, check passes | | `author_id` changed to a missing id | author loaded as nil, fails | | `optional: true` | no check at all | ## Validation is not integrity The check runs in Ruby, at save time, inside your process. It cannot stop another request from deleting the author a millisecond later, and it is skipped entirely by APIs that bypass validations (`update_column`, `insert_all`, raw SQL). Real referential integrity comes from a database foreign key constraint added in the migration, which is a migrations topic. The two complement each other: the validation produces a friendly error message for users, the constraint guarantees the invariant. ## How the default interacts with tests and seeds Because every `belongs_to` is required, test data has to build complete graphs. A fixture row for `books` needs an `author` label, and a factory for `Book` needs an `author` association, or the record fails with "must exist" before the behaviour under test is reached. The fix is to give the fixture or factory its parent, not to sprinkle `optional: true` across models to make tests pass: that silently changes production behaviour too. The same applies to seeds and data imports. An importer that creates books before their authors will fail row by row; create parents first, or wrap the import so that each child is built from an already saved parent. ## Practical guidance - Keep the default for parents a child cannot live without (a book's edition, a listing's book). - Use `optional: true` only where the domain really allows a missing parent, and make the column nullable to match. - If you see "must exist" in a test, check the factory or fixture first: the child was probably built without its parent.
- Does belongs_to :author, optional: true let you store an author_id that points at no author?Yes, as far as Rails is concerned: with `optional: true` there is no presence check, so a dangling id saves unless the database has a foreign key constraint. Even with the default required check, only a nil or changed key is verified. Use a database constraint when integrity matters.
- Why did Rails 7.1 change when the required check runs?Validating the association means reading the parent, which costs a query when it is not already loaded. Before the 7.1 defaults that happened on every save, even when the key had not moved. With `belongs_to_required_validates_foreign_key` set to `false`, Rails validates only when the key is nil or changed, which is when the answer can differ.
- validate: false on belongs_to turns off the "must exist" check.
- The "must exist" check is enforced by a database foreign key constraint.
- In Rails 8.1 belongs_to is optional unless you add required: true.
- With load_defaults 8.1, every save reloads the author to validate it.
- optional: true also makes the author_id column nullable.
Assumes Rails 8.1 with load_defaults 8.1: belongs_to is required since the 5.0 defaults, and since the 7.1 defaults the check runs only when the key is nil or changed.