skip to content

In a Rails 8.1 model, when do you reach for serialize, store or store_accessor, and why must serialize name its coder?

level: seniorimportance: should knowfreq 30%

answer

  1. one Ruby value in a text column
  2. default_column_serializer is nil since 7.1
  3. coder: JSON returns string keys
  4. YAML safe_load permits Symbol only
  5. store_accessor for native JSON columns

basics

~20 s

serialize keeps one Ruby value in a text column through a coder, which load_defaults 7.1 and later make mandatory; store wraps serialize for a hash with named accessors; store_accessor adds accessors to a native JSON column or existing store without another serializer.

solid answer

~40 s

`serialize :extras, coder: JSON` dumps a Ruby value into a text column on save and loads it on read. Since `load_defaults 7.1`, `config.active_record.default_column_serializer` is `nil`, so `serialize` without `coder:` raises `ArgumentError`; the old implicit YAML default was slow and a security risk. The coders behave differently: JSON goes through Active Support's encoder, so a hash comes back with string keys and symbols or times come back as strings; YAML uses `safe_load` and `safe_dump` and rejects classes beyond the permitted list, only `Symbol` by default. `store :delivery_prefs, accessors: [:ring_bell], coder: JSON` is a thin wrapper around `serialize` for a hash, with indifferent access and dirty-tracked accessors. On a native json column the adapter already converts, so use `store_accessor :prefs, :ring_bell`. None of them lets SQL filter on the keys cheaply.

code

ruby · 13 lines
ruby
class Order < ApplicationRecord
  serialize :extras, coder: JSON                      # text column
  serialize :audit, coder: YAML, yaml: { permitted_classes: [Time] }
  store :delivery_prefs, accessors: [:ring_bell, :leave_at_door], coder: JSON
end

order = Order.create!(extras: { crust: :thin }, ring_bell: false)
order.reload.extras    # => {"crust" => "thin"}
order.ring_bell = true
order.ring_bell_was    # => false

# On a native json column, add accessors only:
# store_accessor :prefs, :ring_bell

go deeper

for a junior

Know that serialize stores a Ruby value in one column, and that a new Rails 8.1 app needs coder: JSON or coder: YAML spelled out.

for a middle

Explain how JSON and YAML round-trips differ, and when store or store_accessor is the better declaration.

for a senior

Treat the coder as a data format with security and migration costs: restrict YAML classes, prefer primitives, and move queried keys into columns.

for a principal

Set a policy for semi-structured data: which data may live in serialized columns, which coder, and when it graduates to real columns.

## Three tools, one idea All three keep structured data in a single column of a row, read and written as Ruby objects: | Macro | Column | What you get | |---|---|---| | `serialize :extras, coder: JSON` | text | one Ruby value, dumped on save and loaded on read | | `store :delivery_prefs, accessors: [:ring_bell], coder: JSON` | text | a hash with indifferent access plus an attribute-style accessor per key | | `store_accessor :prefs, :ring_bell` | native json, or an existing store | accessors only; the adapter or the store does the conversion | ## Why serialize needs a coder `serialize(attr_name, coder: nil, type: Object, comparable: false, yaml: {}, **options)` falls back to `default_column_serializer` when no coder is given. The framework default is the YAML coder, but `config.load_defaults 7.1` sets `config.active_record.default_column_serializer = nil`, and every new Rails 8.1 app runs `load_defaults 8.1`. So `serialize :extras` alone raises `ArgumentError` (`missing keyword: :coder`) when the model loads. The configuration guide explains the reason: YAML was an inefficient default and a source of vulnerabilities when misused, so Rails makes you choose. ## How the coders differ - **`coder: JSON`** is routed through Active Support's JSON encoder, which honours `as_json`. Round-trips lose Ruby types: `{ crust: :thin }` comes back as `{"crust" => "thin"}`, and a `Time` comes back as a string. - **`coder: YAML`** keeps more types but loads with `Psych.safe_load`, and on Psych 5.1 or later dumps with `safe_dump`, both limited to basic types plus `config.active_record.yaml_column_permitted_classes`, which defaults to `[Symbol]`. Saving a `Time` therefore raises `Psych::DisallowedClass` unless you widen the list, per column with `yaml: { permitted_classes: [Time] }` or globally. - **A custom coder** is any object with `load` and `dump`. Converting a value object to and from primitives this way is the documented way to keep the format stable as the class evolves. ## Useful options 1. `type: Hash` enforces the class of the value: assigning anything else raises `ActiveRecord::SerializationTypeMismatch`, and a `NULL` column reads as `Hash.new`. 2. `comparable: true` compares deserialized values for dirty tracking instead of the serialized text, which avoids false changes when two equal hashes encode differently. 3. In-place edits such as `order.extras["crust"] = "thick"` are detected, because Rails compares the newly encoded value with the stored one. ## store and store_accessor `store` calls `serialize` with a wrapper coder that turns the hash into a `HashWithIndifferentAccess`, then defines accessors. Without `coder:` it still falls back to YAML through that wrapper, so pass `coder: JSON` explicitly. Each accessor comes with dirty methods: `ring_bell_changed?`, `ring_bell_was`, `ring_bell_change`, `saved_change_to_ring_bell?` and `ring_bell_before_last_save`. `Order.stored_attributes` lists the keys per store. `store_accessor` only defines those accessors. Use it on a native json column, where adding `serialize :prefs, coder: JSON` raises `ColumnNotSerializableError` once the model loads its schema, because the column type already serializes, or to add keys to an existing `store`. ## Limits that decide the choice - Keys inside a text column cannot be used in hash conditions: `Order.where(ring_bell: true)` refers to a column that does not exist. - Values are not type-cast; override the accessor and call `super` to cast. - Uniqueness validations do not work on store keys. ## Migrating away from YAML Older apps often have YAML in these columns from the implicit default. Moving to JSON is a data migration, not a one-line change: 1. declare the column with `coder: YAML` explicitly, so behaviour stays the same under `load_defaults 7.1`, 2. backfill each row by loading it with the YAML coder and writing JSON, typically in a separate column, 3. switch the model to the new column with `coder: JSON` once every row is converted. When a key needs querying, indexing or constraints, it deserves a real column. Database-specific JSON operators and flexible-schema design are separate topics.

  • What happens if you declare serialize :prefs, coder: JSON on a native json column?
    Rails raises `ActiveRecord::AttributeMethods::Serialization::ColumnNotSerializableError` as soon as the model loads its column types, because the json column type already converts between JSON text and Ruby hashes. Drop `serialize` and use `store_accessor` for named keys.
  • Why is Marshal a poor coder choice for a column?
    Like unrestricted YAML, Marshal can rebuild arbitrary Ruby objects, so loading data you do not fully control is unsafe, and the stored bytes are tied to class definitions that may change. The Rails docs recommend converting values to primitives of a stable format instead.

  • serialize without coder: still defaults to YAML in a new Rails 8.1 app
  • coder: JSON round-trips symbols and times back to their Ruby types
  • The YAML coder loads any class by default
  • store_accessor keys can be queried with Order.where(ring_bell: true)
  • A native json column needs serialize with coder: JSON as well

Assumes Rails 8.1 with load_defaults 7.1 or later, where serialize needs an explicit coder:, on Ruby 4.0, whose Psych 5.3 lets the YAML coder dump with safe_dump.