skip to content

In Active Record, what changes when you set autosave: true on a has_many, compared with leaving autosave unset or setting it to false?

level: seniorimportance: should knowfreq 33%

answer

  1. false is not the same as unset
  2. default saves only new children
  3. changed_for_autosave? on loaded records
  4. mark_for_destruction waits for save
  5. nested errors like cards.title

basics

~20 s

Unset, saving the parent saves only new children. autosave: true also saves changed loaded children, destroys ones marked with mark_for_destruction and copies their validation errors onto the parent, all in one transaction. autosave: false saves no children at all.

solid answer

~40 s

`autosave:` has three states. Left unset, `board.save` inserts newly built cards but ignores edits to persisted cards. With `autosave: true`, every loaded card that is new, changed or marked with `mark_for_destruction` is saved or destroyed during `board.save`, the cards are validated as part of the board with errors like `cards.title`, and everything runs in the board's transaction. With `autosave: false`, nothing is saved, not even new cards. Autosave only looks at records already loaded in the association; a card fetched separately with `Card.find` is not covered. `accepts_nested_attributes_for` enables `autosave: true` for its association. The cost is invisible writes: any loaded child changed anywhere is persisted on the next parent save.

code

ruby · 12 lines
ruby
class Board < ApplicationRecord
  has_many :cards, autosave: true
end

board = Board.includes(:cards).find(7)
board.cards.first.title = ""          # invalid edit
board.cards.last.mark_for_destruction
board.save                            # => false, nothing written
board.errors.full_messages            # => ["Cards title can't be blank"]

board.cards.first.title = "Triage"
board.save                            # => true: card updated, last card destroyed

go deeper

for a junior

Recall that by default saving a parent saves only new children, and that autosave: true is needed for edits to existing ones.

for a middle

Explain the three states, mark_for_destruction, nested error keys, and that autosave only sees records loaded in the association.

for a senior

Use autosave: true where the parent is the edited aggregate, and watch for invisible writes, large loaded collections and callback ordering.

for a principal

Define aggregate boundaries explicitly: which roots may write their children on save, and where explicit service code should persist records instead.

## Three states, not two `autosave:` decides whether saving a parent also saves, validates and destroys its associated records. It has three states, and the docs stress that **`autosave: false` is not the same as leaving it out**: | Setting on `has_many :cards` | New cards | Changed persisted cards | Cards marked for destruction | |---|---|---|---| | not set (default) | saved with the board | **not** saved | ignored | | `autosave: true` | saved | saved | destroyed | | `autosave: false` | **not** saved | not saved | ignored | The same three states apply to `has_one` and `belongs_to`; on a `belongs_to`, the default saves a new parent before the child so the key can be filled in, and `autosave: true` also saves a changed parent. ## The default in practice ```ruby board = Board.find(7) board.cards.build(title: "New") # new record board.cards.first.title = "Renamed" # change to a persisted card board.save ``` Without `autosave:`, the save inserts "New" but **drops "Renamed" on the floor**: the persisted card's change is never written. Developers expecting a unit of work that flushes all dirty objects are surprised; Active Record only writes what is explicitly saved, and the default autosave covers new children only. ## What autosave: true adds 1. **Changed children are saved.** Every loaded card that is new, has unsaved changes, or is marked for destruction is processed. The check is `changed_for_autosave?`. 2. **Destruction on save.** `card.mark_for_destruction` flags a loaded card; it is destroyed when `board.save` runs, inside the board's transaction, not immediately. 3. **Validation with real error names.** Children are validated during the board's validation, and their errors are copied to the board with nested keys such as `cards.title`. With the default, a failing new card only adds a generic "Cards is invalid". 4. **Atomicity.** The board, its children and the destructions all run inside the transaction `save` opens; a failure rolls everything back and `save` returns `false`. `accepts_nested_attributes_for` turns `autosave: true` on for its association, which is why nested forms can update and delete children through one save; the nested-attributes writer itself is a separate topic. ## Only what is loaded Autosave walks the **in-memory** association, never the database. If `board.cards` was not loaded, there is nothing to save, and a card you fetched separately with `Card.find` is a different object that the board knows nothing about. Changes must be made through the board's own loaded collection to be autosaved. ## When the callbacks run Autosave is implemented with callbacks added when the association is declared. In the source, a collection's records are saved in `after_create` / `after_update` callbacks of the parent, while a `belongs_to` parent is saved in a `before_save` so its key exists first. Because callbacks run in declaration order, a parent callback declared before the association that changes the collection can interfere; the docs advise declaring your own callbacks after associations. ## belongs_to and has_one On a `belongs_to`, the default already saves a **new** parent before the child, so `card = Board.new.cards.build(...)` followed by `card.save!` inserts the board too when the inverse is known. `autosave: true` on the `belongs_to` additionally saves a parent that was changed through the child (`card.board.name = "Q3"; card.save`) and destroys a parent marked for destruction. On a `has_one`, the default saves a new associated record with the owner, and `autosave: true` extends that to a changed one. In every case only the record held in memory by the association is considered. ## autosave: false `autosave: false` turns the default off entirely: even new children built through the association are not saved with the parent. It suits associations you always persist explicitly, or cases where an expensive child must never be written by accident. On a `has_many`, new children are still validated with the parent unless you also pass `validate: false`, because collections validate by default. ## When to use which - Leave it unset for ordinary associations where you create children through `create` or save them explicitly. - Use `autosave: true` when the parent is the unit you edit, such as a board form editing its cards, so one `save` validates and writes the whole aggregate. - Use `autosave: false` only deliberately, and say why in a comment. The risk with `autosave: true` is invisible writes: any code that touches a loaded child and later saves the parent persists that change, and large loaded collections are checked one record at a time on every save.

  • Why did editing a card fetched with Card.find(12) and then calling board.save not save the card, even with autosave: true?
    Autosave only processes records held in the board's loaded association. `Card.find(12)` returns a separate object the board does not hold, so `board.save` never sees it. Save it directly, or change it through `board.cards`.
  • How does autosave: true change the validation errors a parent reports?
    Changed children are validated with the parent and their errors are copied onto it under nested keys such as `cards.title`, so forms can show the real problem. Without autosave, an invalid new child only adds a generic `cards` error that reads "Cards is invalid".

  • autosave: false and leaving autosave unset behave the same.
  • Without autosave, board.save writes edits to persisted cards.
  • mark_for_destruction deletes the card immediately.
  • autosave: true queries the database for every child and saves it.
  • Active Record flushes all dirty records at the end of the request.