With Jbuilder in a Rails API, how do json.extract!, json.array! and json.partial! build a flight-search response, and what does as: do?
answer
- uncomment jbuilder in an --api Gemfile
- index.json.jbuilder beside the action
- extract! copies named attributes
- array! with partial: and as:
- as: names a local, not a key
basics
~20 sA Jbuilder template builds JSON with a json object: extract! copies named attributes, array! renders a collection, and partial! renders a shared _flight.json.jbuilder. as: names the local variable each element gets in the partial; it does not add a key.
solid answer
~40 sAfter uncommenting `gem "jbuilder"` (an `--api` app ships it commented), each action can have a template such as `app/views/api/v1/flights/index.json.jbuilder`. Inside it, `json.extract! flight, :flight_number, :departs_at` copies those attributes; `json.key value` sets one key; a block nests an object; `json.array! @flights, partial: "api/v1/flights/flight", as: :flight` renders the partial once per flight and returns a JSON array. Both `partial:` and `as:` are needed for that form. `as:` only names the local variable inside the partial; it does not wrap anything under a `"flight"` key, so to nest, open a block (`json.outbound do ... end`) or use `json.fares flight.fares, partial: "api/v1/fares/fare", as: :fare`. `json.key_format! camelize: :lower` at the top of a template turns `departs_at` into `departsAt` for every key written afterwards in that response, partials included. Because only named fields are written, internal fare columns never appear.
code
ruby · 11 lines# app/views/api/v1/flights/_flight.json.jbuilder
json.extract! flight, :id, :flight_number, :departs_at, :arrives_at
json.duration_minutes flight.duration_minutes
json.fares flight.fares, partial: "api/v1/fares/fare", as: :fare
# app/views/api/v1/fares/_fare.json.jbuilder
json.extract! fare, :cabin, :amount_cents, :currency
# app/views/api/v1/flights/index.json.jbuilder
json.key_format! camelize: :lower
json.array! @flights, partial: "api/v1/flights/flight", as: :flightgo deeper
Know where Jbuilder templates live and what extract!, array! and partial! write.
Explain partial: with as:, the as:-is-not-nesting trap, and instance versus class-level key formatting.
Use templates per API version as allow-lists, and watch partial rendering cost and per-element association loads.
Weigh Jbuilder views against Ruby presenter objects for throughput, testability and version isolation.
## What Jbuilder is **Jbuilder** is a gem from the Rails team that lets you write JSON responses as view templates, the way ERB writes HTML. A file named `index.json.jbuilder` is Ruby code that receives a builder object called `json` and the controller's instance variables. Every key you set becomes a key in the output; nothing else is emitted. That makes a template an **allow-list**: a new `markup_cents` column on `Fare` stays private until someone writes it into a template. In an app generated with `rails new --api`, the `jbuilder` line is commented out in the `Gemfile`. Uncomment it and `bundle install`; the gem registers the `.jbuilder` template handler, and for API controllers it also restores implicit rendering, so an action without `render` uses its matching template. ## The core methods | Call | Output | |---|---| | `json.flight_number flight.flight_number` | `"flight_number": "KJ 118"` | | `json.extract! flight, :id, :origin, :destination` | those keys, values from the readers (or hash keys) | | `json.(flight, :id, :origin)` | the same as `extract!`, shorter | | `json.outbound do ... end` | `"outbound": { ... }` | | `json.array! @flights, :id, :flight_number` | `[ {"id":..,"flight_number":..}, ... ]` | | `json.fares flight.fares, :cabin, :amount_cents` | `"fares": [ {...}, ... ]` | | `json.merge!(hash)` | merges a prepared hash into the current object | | `json.nil!` (or `json.null!`) | makes the current value `null` | ## Partials Shared shapes go in partials, named with a leading underscore: ```ruby # app/views/api/v1/flights/_flight.json.jbuilder json.extract! flight, :id, :flight_number, :departs_at, :arrives_at json.fares flight.fares, partial: "api/v1/fares/fare", as: :fare # app/views/api/v1/flights/index.json.jbuilder json.array! @flights, partial: "api/v1/flights/flight", as: :flight ``` A collection can go through a partial in three ways: `json.array! @flights, partial: ..., as: :flight` and `json.partial! "api/v1/flights/flight", collection: @flights, as: :flight` both produce a bare array, while the keyed form `json.flights @flights, partial: ..., as: :flight` nests the array under `"flights"`. For a single object: `json.partial! "api/v1/flights/flight", flight: @flight`. ## The as: trap `as: :flight` means **"inside the partial, call each element `flight`"**. It does not mean "nest under a `flight` key". So `json.partial! @flight, as: :flight` inlines the flight's keys into the current object. To nest, open a key first: ```ruby json.outbound do json.partial! "api/v1/flights/flight", flight: @outbound end ``` With `json.array!`, Jbuilder treats the options as partial options only when **both** `partial:` and `as:` are present; leave out `as:` and the hash is not read as partial options at all. ## Key formatting and nils - `json.key_format! camelize: :lower` formats keys written **after** it by the same builder, including keys from partials rendered later in that scope, so `departs_at` becomes `departsAt`. Jbuilder restores the previous formatter when a nested scope ends. - `Jbuilder.key_format camelize: :lower` in an initializer sets the default for every template. - Keys inside a plain Hash passed as a value are left alone unless `json.deep_format_keys!` is on. - `json.ignore_nil!` drops keys whose value is `nil` instead of writing `null`. ## Where it fits Jbuilder templates live under `app/views`, next to the controllers' namespaces, so `Api::V1` and `Api::V2` can render different shapes from the same models. The cost is speed: each partial render goes through Action View, which is slower than building a hash in Ruby, and any association a partial touches is loaded per element unless the controller preloads it. ## Testing and debugging templates - Request tests are the natural place: `get api_v1_flights_path, as: :json`, then assert on `response.parsed_body`. They exercise the template, its partials and the key formatting together. - To try a shape in `bin/rails console`, `Jbuilder.encode { |json| json.extract! Flight.first, :id, :flight_number }` returns the JSON string without a request. - A missing template in an API action does not raise; with no template and no `render`, the action answers 204, so a typo in the file name looks like an empty success. - Jbuilder raises its own errors for impossible shapes, for example setting a key after `json.array!` turned the current value into an array, which shows up as a 500 in the request test.
- How do you make every Jbuilder template in the app emit camelCase keys?Call `Jbuilder.key_format camelize: :lower` once, for example in `config/initializers/jbuilder.rb`. The class-level setting becomes the default for every builder, so partials are covered too. Add `Jbuilder.deep_format_keys true` if nested plain hashes passed as values should be camelized as well.
- What is the difference between json.extract! and json.merge!?`extract!` reads the named attributes from an object or hash and writes only those keys. `merge!` takes a whole hash, array or another builder and merges all of it into the current value. `merge!` is useful for prepared data, but it has no allow-list of its own, so merging `fare.attributes` would expose every column.
- as: :flight nests each element under a flight key.
- json.array! @flights, partial: "flights/flight" works without as:.
- json.key_format! in one partial changes every template in the app.
- Jbuilder writes every model column unless a template excludes some.
- jbuilder is active by default in an app generated with --api.