In a Rails controller, what does render json: @flights do, and how do only:, except:, methods: and include: shape the output?
answer
- to_json, then as_json, then serializable_hash
- every column unless you narrow it
- methods: adds, only: and except: filter
- include: takes its own nested options
- a wrapping Hash filters its own keys
basics
~10 srender json: @flights calls to_json, which runs as_json and, for Active Record, serializable_hash on each record. only: and except: choose columns, methods: adds method results, and include: nests associations with their own options.
solid answer
~50 s`render json:` passes any non-String object to `to_json` with the remaining render options, sets the content type to `application/json`, and honours `status:`. Active Support's `to_json` calls `as_json`, and for Active Record `as_json` calls `serializable_hash`. With no options every column is emitted, internal ones included. `only:` keeps the listed columns, `except:` drops them, `methods:` adds the return values of named methods even when `only:` is set, and `include:` nests associations, taking its own hash of options such as `include: { fares: { only: [:amount_cents, :currency] } }`. For an array, each record gets the same options. A trap: `render json: { flights: @flights }, only: [...]` applies `only:` to the wrapping Hash's own keys first, so the result is `{}`. In Rails 8.1 the renderer no longer escapes `<`, `>` and `&` unless you pass `escape: true`.
code
ruby · 10 linesclass Api::V1::FlightsController < ApplicationController
def index
flights = Flight.where(origin: params[:from], destination: params[:to]).includes(:fares)
render json: flights,
only: [:id, :flight_number, :departs_at, :arrives_at],
methods: [:duration_minutes],
include: { fares: { only: [:cabin, :amount_cents, :currency] } }
end
endgo deeper
Recall the chain to_json, as_json, serializable_hash and what each of only:, except:, methods: and include: does.
Explain the nested options of include:, the wrapping-Hash trap and why methods: survives only:.
Argue for allow-lists over except: on models with internal columns, and notice the per-record association loads that include: triggers.
Set a team rule for where response shapes live so a new column cannot leak by default.
## The call chain behind render json: `render json: object` is the shortest way to answer a request with JSON from a Rails controller. Behind it sit four steps: 1. The JSON renderer removes `:callback`, `:content_type` and `:status` from the render options and, unless the object is already a `String`, calls `object.to_json(remaining_options)`. 2. Active Support's `to_json` hands the object and the options to `ActiveSupport::JSON.encode`. 3. The encoder calls `as_json(options)` on the object, which must return plain Ruby data: hashes, arrays, strings, numbers, booleans, nil. 4. For an Active Record model, `as_json` calls **`serializable_hash(options)`**, which builds the hash from the model's attributes and the options. The renderer also sets `Content-Type: application/json` when no other type was chosen, and `status:` sets the HTTP status. A `String` passes through untouched, so `render json: payload_string` sends exactly that text. ## The four shaping options | Option | Effect on each record | Example | |---|---|---| | none | every column, including internal ones | `render json: @flight` | | `only:` | keep just these attributes | `only: [:flight_number, :departs_at]` | | `except:` | every attribute except these | `except: [:created_at, :updated_at]` | | `methods:` | add the return value of each named method | `methods: [:duration_minutes]` | | `include:` | nest associations, each with its own options | `include: { fares: { only: [:amount_cents] } }` | Three details matter in interviews: - `only:` wins if both `only:` and `except:` are given; `except:` is then ignored. - `methods:` is applied **after** `only:`/`except:`, so a method listed there appears even when `only:` does not name it. - Keys come out as strings, and values go through `as_json` too, so times become ISO 8601 strings with millisecond precision. ## Nesting with include: `include:` accepts a symbol, an array or a hash. The hash form passes options down one level, and can nest further: ```ruby render json: @flights, only: [:id, :flight_number, :origin, :destination, :departs_at], methods: [:duration_minutes], include: { fares: { only: [:cabin, :amount_cents, :currency] } } ``` For each flight Rails calls `flight.fares` and then `serializable_hash` on every fare with the nested options. Two consequences follow: each record's association is loaded one by one unless the relation was preloaded, and the child's own `as_json` override is **not** used, because the parent calls the child's `serializable_hash` directly. ## Collections and wrapping hashes When the object is an `Array` or a relation, Active Support's `Array#as_json` passes the same options to every element, so `render json: @flights, only: [...]` shapes each flight. A `Hash` is different: `Hash#as_json` applies `only:` and `except:` to **its own keys** before passing the options to its values. So: ```ruby render json: { flights: @flights }, only: [:flight_number] # => {} -- the Hash has no :flight_number key ``` To wrap a collection under a key, shape it first: `render json: { flights: @flights.as_json(only: [:flight_number]) }`. ## What these options do not protect The default is **everything**. A `Fare` row with `net_cost_cents`, `markup_cents` and `fare_basis_code` sends them all to the client unless every call site remembers `except:`. `config.filter_parameters` and the model's `filter_attributes` only mask values in logs and `inspect`; they do not touch JSON output. For anything sensitive, use an allow-list (`only:`, a Jbuilder template, or a `serializable_hash` override on the model) so a new column is hidden until someone deliberately exposes it. ## Escaping in Rails 8.1 Before 8.1, the renderer escaped `<`, `>`, `&` and the JavaScript line separators U+2028 and U+2029 as `\u003c`-style sequences, so JSON could be pasted into a `<script>` tag safely. With `config.load_defaults 8.1`, `config.action_controller.escape_json_responses` is `false`: `render json:` emits those characters as-is, which is correct for an `application/json` response and faster. Escaping still happens with the JSONP `callback:` option, and `render json: data, escape: true` restores it per call when the JSON will be embedded in HTML. ## Pinning the shape in a test Because the default exposes every column, a request test that checks the **exact key set** catches leaks when someone adds a column or an `include:`: ```ruby get api_v1_flights_path(from: "VIE", to: "LIS"), as: :json flight = response.parsed_body.first assert_equal %w[arrives_at departs_at duration_minutes fares flight_number id], flight.keys.sort assert_equal %w[amount_cents cabin currency], flight["fares"].first.keys.sort ``` `response.parsed_body` parses the JSON according to the response's content type, so the test reads plain hashes. An `except:`-based endpoint fails this test the day `markup_cents` is added, which is exactly when you want to hear about it.
- Why does render json: { flights: @flights }, only: [:flight_number] return an empty object?`Hash#as_json` applies `only:` and `except:` to the hash's own keys before passing the options down to the values. The wrapper has only a `:flights` key, so slicing it to `:flight_number` leaves nothing. Shape the inner collection first, for example `{ flights: @flights.as_json(only: [:flight_number]) }`.
- When would you pass escape: true to render json: in Rails 8.1?When the JSON will be embedded in an HTML page, for example interpolated into a `<script>` tag, because a value containing `</script>` could break out of it. With `load_defaults 8.1` the renderer emits `<`, `>` and `&` unescaped for speed; `escape: true` restores the `\u003c`-style escaping for that one call, and JSONP's `callback:` always escapes.
- render json: @fare returns only the attributes exposed in the controller.
- filter_attributes on the model keeps net_cost_cents out of render json:.
- only: also removes the attributes added through methods:.
- only: on a wrapping Hash is passed straight to the nested records.
- Rails 8.1 still escapes < and > in every render json: response.
Assumes Rails 8.1 with config.load_defaults 8.1, where escape_json_responses is false and render json: stops escaping <, >, & and U+2028/U+2029 unless escape: true or callback: is used.