skip to content

In an Active Record model, why can assigning book.tag_ids or calling book.tags << tag change the database before book.save fails, and how do you keep it atomic?

level: seniorimportance: should knowfreq 32%

answer

  1. persisted owner, write on the call
  2. no unit of work to flush
  3. _ids= runs its own transaction
  4. build waits, create and << do not
  5. update wraps assign plus save

basics

~20 s

On a persisted owner, collection writers such as tag_ids=, tags= and << write immediately in their own transaction, so a later failed save cannot undo them. Use update, which wraps assignment and save in one transaction, or an explicit transaction with save!.

solid answer

~40 s

Active Record writes on the call; it has no unit of work that flushes at save time. On a persisted book, `tag_ids=` loads the tags, then deletes removed links and inserts new ones in its own transaction, and `<<` and `tags.create` insert straight away. `build` and assigning a `belongs_to` stay in memory until `save`. So `assign_attributes(title: "", tag_ids: [3])` followed by a failing `save` leaves the tags changed. `update(attributes)` exists for this: it runs the assignment and the save in one transaction and rolls back when `save` returns false. Otherwise wrap the work in `Book.transaction` with `save!`. A has_one writer has the same trait and also saves the replaced record.

code

ruby · 10 lines
ruby
book = Book.find(42)                     # persisted, tags [1, 2]

book.assign_attributes(title: "", tag_ids: ["", "3"])
# links already rewritten here: DELETE tagging rows for 1, 2; INSERT for 3
book.save                                # => false (title blank)
book.reload.tag_ids                      # => [3]  the change survived

book.update(title: "", tag_ids: ["", "1", "2"])
# => false; assignment and save shared one transaction, rolled back
book.reload.tag_ids                      # => [3]

go deeper

for a junior

Recall which association calls save immediately on a persisted record (<<, create, ids and collection writers) and which wait for save (build, belongs_to assignment).

for a middle

Explain that each writer opens its own transaction, why that escapes a later failed save, and what tag_ids= does with blank and unknown ids.

for a senior

Diagnose partial writes in edit flows, fix them with update or an explicit transaction, and watch has_one replacement saving the old row behind your back.

for a principal

Set a team rule for multi-model writes: one transaction per user action, built with update or save!, so association side effects never escape a failed validation.

## The surprise A team's book edit form posts a title and a list of tag ids. The controller action does this: ```ruby book.assign_attributes(title: params_title, tag_ids: params_tag_ids) if book.save # ... else render :edit, status: :unprocessable_content end ``` When the title is blank, `save` fails, the form re-renders, and yet the book's tags **have already changed** in the database. Nothing is wrong with validations. The cause is that Active Record association writers on a **persisted** owner write immediately, on the call, not when the owner is saved. ## Which calls write when Active Record has no unit of work that collects changes and flushes them at the end. Each association method decides on its own whether to touch the database: | Call (owner persisted) | Writes now? | What it does | |---|---|---| | `book.tag_ids = [3, 5]` | yes | loads the tags, deletes removed links, inserts new ones | | `book.tags = [tag]` | yes | the same replacement, given records | | `book.tags << tag` | yes | inserts the link (with `save!` on a through join model) | | `book.tags.create(name: "sci-fi")` | yes | inserts the tag and the link | | `book.tags.build(name: "sci-fi")` | no | in memory until `book.save` | | `book.author = author` | no | sets `author_id` in memory; written by `book.save` | | `book.build_author` / `book.create_author` | no / yes | build stays in memory; create inserts the author, the book's key is set in memory only | | `author.biography = bio` | yes | saves the new biography and updates or removes the replaced one | On a **new** owner the picture changes: `<<`, `tags=` and `tag_ids=` only update the in-memory collection, and everything is inserted when the owner is first saved. `tags.create` on a new owner raises `ActiveRecord::RecordNotSaved` ("You cannot call create unless the parent is saved"). ## Why tag_ids= in particular bites `tag_ids=` is the method form builders and APIs hit most often. On a persisted book it: 1. drops blank entries (the hidden empty value a checkbox group sends) and casts the rest; 2. loads the matching `Tag` records, raising `ActiveRecord::RecordNotFound` if any id is unknown; 3. calls the collection writer, which diffs old and new and, inside its **own** transaction, deletes the removed links and inserts the added ones. On a `has_many :through`, removed join rows go with a direct `DELETE` by default, so `Tagging` destroy callbacks do not run, while added rows are created with `save!`, so `Tagging` validations and create callbacks do run and a failure raises `ActiveRecord::RecordInvalid`. Because that transaction finishes before `book.save` is even called, a later validation failure on the book cannot undo it. ## The fixes - **Use `update`, not `assign_attributes` plus `save`.** `update(attributes)` wraps both the assignment and the save in one transaction; the source comment says this exists to cover side effects of assignment "for example, setting the IDs of a child collection". If `save` returns false, the transaction rolls back and the links revert. - **Wrap it yourself** when the flow is more complex: `Book.transaction { book.assign_attributes(...); book.save! }`, letting the exception roll everything back. - **Validate before touching associations** when the work cannot be in one transaction. - **Use `build` and save once** for new child records, so nothing is written until the owner saves. ## The has_one variant Singular associations have the same trait with a sharper edge. Assigning a new record to `has_one :biography` on a persisted author saves the new biography *and* the one it replaces, setting the old row's `author_id` to `NULL`; if either save fails, `ActiveRecord::RecordNotSaved` is raised. Even `author.build_biography`, which does not save the new object, still saves the replaced biography to clear its key. On a `NOT NULL` column that surfaces as a database error from a method whose name suggests nothing is written. ## What to say in the interview Show that you know Active Record writes on the call: name the methods that hit the database on a persisted owner, explain that each runs in its own transaction, and give `update` (or an explicit transaction) as the fix. Saying "Rails batches the changes and flushes on save" is the red flag: that is another ORM's model, not Active Record's.

  • Does author.build_biography write anything when the author already has a biography?
    It can. `build_biography` does not save the new record, but replacing a `has_one` still saves the old biography with its `author_id` set to nil (or deletes or destroys it when the association has `dependent: :delete` or `:destroy`), and raises `ActiveRecord::RecordNotSaved` if that save fails.
  • What does tag_ids= do with an id that matches no tag?
    It raises `ActiveRecord::RecordNotFound` before changing anything, because it loads every listed record first. Blank strings, such as the empty value a checkbox group submits, are dropped before the lookup.

  • Active Record queues association changes and flushes them on save.
  • tag_ids= on a persisted book waits for book.save to write links.
  • A failed book.save rolls back links that tag_ids= already wrote.
  • book.tags.build inserts the tag immediately on a persisted book.
  • update and assign_attributes followed by save are equivalent.