In an Active Record model, how do you override as_json safely, and why can a parent's include: skip that override?
answer
- options may be nil or frozen
- merge into a new hash, call super
- include: calls serializable_hash
- override serializable_hash for every path
- one model, one default shape
basics
~10 sOverride as_json(options = nil) by calling super with a new options hash, never by mutating options. A parent's include: calls the child's serializable_hash, not as_json, so field-hiding that must always apply belongs in serializable_hash.
solid answer
~40 sAn `as_json(options = nil)` override should build a new hash and call `super`, for example `super({ only: PUBLIC }.merge(options || {}))`. Writing into `options` breaks: it is nil when the method is called bare, and frozen when Rails passes options through a collection. Avoid `to_json` overrides too, because nested records are serialized through `as_json`. The bigger trap is `include:`: when a `Flight` is rendered with `include: :fares`, Rails calls each fare's `serializable_hash` directly, so a `Fare#as_json` that hides `net_cost_cents` is skipped and the internal column leaks. Hiding that must hold on every path goes in a `serializable_hash` override, for example `super(options).except("net_cost_cents", "markup_cents")`. Once one model needs several shapes (search list, booking detail, admin), move shaping out of the model into Jbuilder views or a presenter.
code
ruby · 10 linesclass Fare < ApplicationRecord
belongs_to :flight
INTERNAL = %w[net_cost_cents markup_cents fare_basis_code].freeze
# Applies to render json: fare, collections, and include: :fares on a flight
def serializable_hash(options = nil)
super(options).except(*INTERNAL)
end
endgo deeper
Know that as_json and serializable_hash control a model's default JSON and that overrides call super.
Trace which callers hit as_json and which hit serializable_hash, and why mutating options breaks.
Put never-public columns behind a serializable_hash filter and move per-endpoint shapes out of the model.
Decide how a codebase enforces response allow-lists so one forgotten include: cannot leak internal fields.
## Two hooks on every Active Record model An Active Record model gets its JSON behaviour from **`ActiveModel::Serializers::JSON`**, included through `ActiveRecord::Serialization`. Two methods matter: - **`as_json(options = nil)`** is what Active Support's encoder calls on an object. For a model it handles the `root:` option and then calls `serializable_hash(options)`. - **`serializable_hash(options = nil)`** builds the attribute hash, applying `only:`, `except:`, `methods:` and `include:`. Active Record's version also drops the inheritance column (`type`) when the table has one. Overriding either changes the model's default JSON. Which one you pick decides which code paths see the change. ## Who calls which | Caller | Method it calls on the record | |---|---| | `render json: fare` | `to_json`, then `as_json`, then `serializable_hash` | | `render json: [fare1, fare2]` | `as_json` on each fare | | `fare.as_json` in your code | `as_json` | | `render json: flight, include: :fares` | **`serializable_hash`** on each fare, directly | | `flight.as_json(include: :fares)` | **`serializable_hash`** on each fare, directly | The last two rows are the trap. `serializable_hash` on the parent loops over the association and calls `record.serializable_hash(nested_options)` on each child. A `Fare#as_json` override never runs on that path. ## A safe as_json override When you do override `as_json`, two rules keep it from breaking callers: 1. **Never mutate `options`.** It is `nil` when called as `fare.as_json`, and Rails passes a frozen hash when it serializes a collection with options, so `options[:except] = [...]` raises `NoMethodError` or `FrozenError` depending on the path. 2. **Build a new hash and call `super`.** Decide whether caller options may override yours. ```ruby def as_json(options = nil) super({ only: %i[id cabin amount_cents currency] }.merge(options || {})) end ``` Here a caller's `only:` replaces the default, which is convenient but means any caller can re-expose a column. If a field must **never** leave the server, filter the result instead of the options. ## Hiding a field on every path ```ruby class Fare < ApplicationRecord INTERNAL = %w[net_cost_cents markup_cents fare_basis_code].freeze def serializable_hash(options = nil) super(options).except(*INTERNAL) end end ``` Because `as_json` calls `serializable_hash`, and `include:` calls it too, this one override covers `render json: fare`, collections, and fares nested under flights. Keys in the result are strings, so the list is strings too. A caller's `only: [:net_cost_cents]` still cannot get the column back, which is the point. ## Why not override to_json `render json:` happens to call `to_json` on the top-level object, so a `to_json` override seems to work in a quick test. But the encoder serializes anything nested (records inside an array or a hash, associations) through `as_json`, never `to_json`. A `to_json` override therefore silently stops applying the moment the record is wrapped or nested. ## When the model is the wrong place An override gives the model **one** default shape. That works while every endpoint wants the same fields. It strains when: - a search list wants a summary and a booking page wants detail; - an `Api::V2` changes field names while `Api::V1` must not change; - the shape depends on who is asking, such as an internal operations tool that may see `markup_cents`. At that point keep the model's `serializable_hash` as a safety net for never-public columns, and put endpoint shapes in Jbuilder templates or a small presenter class whose `as_json` builds the hash explicitly. ## Testing the safety net One model test covers every path at once, because it exercises the nested route that bypasses `as_json`: ```ruby test "internal fare columns never serialize" do json = flights(:vie_lis).as_json(include: :fares) assert json["fares"].none? { |fare| fare.key?("net_cost_cents") } assert_not fares(:economy).as_json(only: [:net_cost_cents]).key?("net_cost_cents") end ``` The second assertion checks that a caller cannot opt the column back in, which an `as_json` override built on `merge` would allow. ## A presenter instead of a model override When endpoints need different shapes, a plain class with an explicit hash keeps each shape in one place and is trivially testable: - `FareSummary.new(fare).as_json` returns `{ "cabin" => ..., "amount_cents" => ..., "currency" => ... }`. - The controller calls `render json: fares.map { |fare| FareSummary.new(fare) }`. - The model keeps only its `serializable_hash` filter as the last line of defence.
- Why does mutating options inside as_json fail only some of the time?It depends on the caller. Called bare, `options` is nil and `options[:except] = ...` raises `NoMethodError`. Rendered with options inside a collection, `Array#as_json` and the encoder pass a frozen hash, so the same line raises `FrozenError`. A test that only calls `fare.as_json(except: [])` on a single record may pass while production breaks.
- Does a serializable_hash override also change what Rails writes to the log or to inspect?No. `serializable_hash` only feeds serialization. `inspect` and logs use the model's `filter_attributes`, which masks values in `inspect` and console output but leaves JSON untouched. You usually want both: `filter_attributes` for logs, a `serializable_hash` filter for responses.
Overriding as_json is like stamping documents at the front desk, but include: carries files out through the records room; redacting in serializable_hash is redacting in the records room itself, which every exit passes through.
- Overriding to_json is enough because render json: calls to_json.
- A Fare#as_json override also applies when Flight includes :fares.
- Setting options[:except] inside as_json is the idiomatic override.
- filter_attributes hides net_cost_cents from as_json output.
- Every endpoint should share one as_json shape per model.