In Active Record STI, what do becomes and becomes! do, and which one changes what is saved to the type column?
answer
- same attributes, different class
- shared attribute set, not a copy
- render or route as the parent
- becomes! writes sti_name
- base class gets NULL
basics
~20 sbecomes(klass) returns an instance of another class sharing the record's attributes, leaving the type column alone, which suits rendering or routing as the parent. becomes!(klass) also writes the new class into the type column, so saving reclassifies the row.
solid answer
~40 s`becomes(Vehicle)` hands back a `Vehicle` instance that shares the same attribute set as the `Truck` it came from, plus its new-record, destroyed and error state. The `type` column is untouched, so it is for presentation: `form_with model: @truck.becomes(Vehicle)` builds `vehicle_path` and `vehicle[...]` field names, and `render @truck.becomes(Vehicle)` uses the vehicles partial. Saving it does not reclassify anything. `becomes!(Truck)` does the same and then writes `Truck.sti_name` into the inheritance column, so `van.becomes!(Truck).save!` turns the row into a truck and runs `Truck`'s validations. Because the attributes are shared, the original `van` sees the new type too. Pass the base class to `becomes!` and the column is set to NULL, not `"Vehicle"`.
code
ruby · 14 linesvan = Van.find(17)
truck = van.becomes!(Truck)
truck.payload_tonnes = 3.5
truck.save!
# UPDATE "vehicles" SET "type" = 'Truck', "payload_tonnes" = 3.5, ...
# WHERE "vehicles"."id" = 17
van.type # => "Truck" (same attribute set)
Vehicle.find(17).class # => Truck
shown = truck.becomes(Vehicle)
shown.type # => "Truck" (becomes leaves it alone)
shown.class # => Vehiclego deeper
Recall that becomes changes only the class an object presents as, while becomes! also changes the stored type once saved.
Explain the shared attribute set, why forms and partials follow the object's class, and why becomes!(Vehicle) writes NULL rather than the base name.
Show you reclassify safely: set the new class's required fields first, let its validations run, and avoid using the original object afterwards.
Weigh local becomes calls against overriding model_name on subclasses, and whether frequent reclassification signals that STI is the wrong model.
## Two ways to see one record as another class In a **single-table inheritance (STI)** hierarchy, `Van`, `Truck` and `EBike` inherit from `Vehicle` and share the `vehicles` table, with the class name stored in the `type` column. Sometimes code needs the same row as a different class: a form that should post to the vehicles controller, or a van that has been reclassified as a truck. Active Record has two methods for that, both on any model instance. ## becomes(klass) `becomes` allocates an instance of `klass` and wires it to the original record: - It shares the **same attribute set object**, not a copy, so a change made through either object shows up on both. - It carries over the original's `new_record?`, `destroyed?`, `previously_new_record?` and `marked_for_destruction?` state, and copies its validation errors. - It leaves the **inheritance column unchanged**: a truck seen as a `Vehicle` still has `type = "Truck"`. That makes it a presentation tool. Action Pack derives routes, partial paths and parameter keys from the object's class, so: 1. `form_with model: @truck.becomes(Vehicle)` posts to `vehicle_path(@truck)` and names fields `vehicle[plate]`. 2. `render @truck.becomes(Vehicle)` renders `vehicles/_vehicle` instead of `trucks/_truck`. 3. `link_to "Show", @truck.becomes(Vehicle)` links to `/vehicles/:id` when only `resources :vehicles` exists. Saving the `becomes` copy writes nothing new about the class: the row keeps its stored type. ## becomes!(klass) `becomes!` calls `becomes` and then writes into the inheritance column: - the target's `sti_name` (for example `"Truck"`) when the target is a subclass; - `nil` when the target is the **base class** itself, because base-class rows carry no type. Because the two objects share attributes, the original object's `type` changes as well. Nothing is written until you save. Saving then issues an `UPDATE` that sets `type`, and it runs the **new class's** validations and callbacks, which is the point: a van promoted to a truck must now satisfy `Truck`'s `validates :payload_tonnes, presence: true`. ## What the copy carries into a form Because `becomes` copies state as well as attributes, the presented object behaves like the original inside a view: - **`new_record?` is preserved**, so `form_with` picks `POST` to the collection for an unsaved truck and `PATCH` to the member for a saved one. - **Errors are copied** at the moment you call `becomes`. In an `update` action that fails, calling `@truck.becomes(Vehicle)` in the re-rendered form shows the truck's validation messages beside the fields; calling it before `update` would copy an empty error list. - **Dirty tracking is shared**, so `changed?` on the copy reflects edits made through the original. This is why `becomes` is usually written in the view or form partial, at the last moment, rather than stored in an instance variable early in the action. ## Which one to use | Goal | Method | Effect on `type` | |---|---|---| | Form or link through the parent's routes | `becomes(Vehicle)` | unchanged | | Render the parent's partial | `becomes(Vehicle)` | unchanged | | Reclassify a van as a truck | `becomes!(Truck)` then `save!` | becomes `"Truck"` | | Demote a subtype to a plain vehicle | `becomes!(Vehicle)` then `save!` | becomes NULL | ## Traps - **`becomes` then `save` does not reclassify.** The class in memory changed; the stored type did not. - **Shared state cuts both ways.** Assigning `payload_tonnes` on the `becomes!` copy assigns it on the original as well; treat the original as gone once you call it. - **Errors after reclassifying.** If `Truck`'s validations fail, `save!` raises `ActiveRecord::RecordInvalid` and the row keeps its old type; set the truck-only fields before saving. - **The routing alternative.** Instead of calling `becomes` in every view, a subclass can return the parent's naming with `def self.model_name = Vehicle.model_name`, so routes and param keys use `vehicle` everywhere. That is a global choice; `becomes` is a local one.
- What does truck.becomes!(Vehicle) write into the type column?NULL. `becomes!` writes the target's `sti_name` only when the target is not the base class; for the base class itself it writes `nil`, matching rows created as plain `Vehicle` records.
- When would you override model_name on STI subclasses instead of calling becomes?When every view, form and link should treat the subtypes as vehicles. `def self.model_name = Vehicle.model_name` on each subclass makes route helpers, partial paths and param keys use `vehicle` everywhere, at the cost of never getting subtype routes automatically.
- Saving the object returned by becomes(Truck) changes the stored type to Truck.
- becomes returns an independent copy, so edits to it never touch the original.
- becomes!(Vehicle) stores the string "Vehicle" in the type column.
- becomes! saves the record immediately with the new type.