In a Rails 8.1 API controller, how do you return a failed save's validation errors as JSON, and what shapes can the errors object produce?
answer
- render json: record.errors
- attribute to messages Hash
- as_json(full_messages: true)
- details carries error codes
- :unprocessable_content for 422
basics
~10 srender json: booking.errors, status: :unprocessable_content sends a Hash of attribute names to message arrays. as_json(full_messages: true) gives full sentences, full_messages a flat list, and details machine-readable codes such as :blank.
solid answer
~40 sThe generated API scaffold does it in one line: `render json: @booking.errors, status: :unprocessable_content`. `ActiveModel::Errors#as_json` returns attribute names mapped to arrays of messages, `{"passenger_name":["can't be blank"]}`. Three other shapes come from the same object: `errors.as_json(full_messages: true)` maps attributes to full sentences (`"Passenger name can't be blank"`); `errors.full_messages` is a flat array of those sentences; and `errors.details` maps attributes to `{ error: :blank }` hashes, the stable codes a mobile client can switch on without parsing English. A common body combines them: `{ errors: booking.errors.details, messages: booking.errors.full_messages }`. In Rails 8.1 on Rack 3.1 or later the 422 symbol is `:unprocessable_content`; `:unprocessable_entity` is Rack's obsolete name and triggers a deprecation warning on Rack 3.2.
code
ruby · 14 linesclass Api::V1::BookingsController < Api::V1::BaseController
def create
booking = Booking.new(params.expect(booking: [:flight_id, :passenger_name, :fare_code]))
if booking.save
render json: booking, status: :created
else
render json: {
errors: booking.errors.details,
messages: booking.errors.full_messages
}, status: :unprocessable_content
end
end
endgo deeper
Know the scaffold line: render json: record.errors with a 422 status, and what the default JSON looks like.
Compare the shapes from as_json, full_messages: true, full_messages and details, and name :unprocessable_content correctly.
Standardise one error body in a base controller, include stable codes, and keep sensitive rejected values out.
Agree an error contract across services and clients so codes stay stable through message rewording and translation.
## The scaffold's answer When `save` returns `false`, the record's **`errors`** object holds what failed. Rails' API scaffold (`bin/rails generate scaffold` in an API app) writes the response like this: ```ruby def create @booking = Booking.new(booking_params) if @booking.save render json: @booking, status: :created, location: @booking else render json: @booking.errors, status: :unprocessable_content end end ``` `render json:` calls `to_json` on the errors object, which calls **`ActiveModel::Errors#as_json`**. That method returns `to_hash`, the attribute-to-messages Hash. ## The four shapes For a booking with a blank passenger name and a two-letter fare code where `length: { minimum: 3 }` applies: | Expression | JSON | |---|---| | `errors` (via `as_json`) | `{"passenger_name":["can't be blank"],"fare_code":["is too short (minimum is 3 characters)"]}` | | `errors.as_json(full_messages: true)` | `{"passenger_name":["Passenger name can't be blank"], ...}` | | `errors.full_messages` | `["Passenger name can't be blank","Fare code is too short (minimum is 3 characters)"]` | | `errors.details` | `{"passenger_name":[{"error":"blank"}],"fare_code":[{"error":"too_short","count":3}]}` | Notes on each: - The default hash suits a web form that shows messages next to fields. - `full_messages: true` prefixes the humanized attribute name, which reads well when the client shows a list. - `details` carries the **error type** as a symbol (`:blank`, `:invalid`, `:taken`, `:too_short`) plus any options the validator recorded, such as `count:` for length or the rejected `value:` for uniqueness and format. These codes do not change when message text is translated or reworded, so clients can rely on them. ## A body for several clients A mobile app wants codes; a web client wants sentences. One body can carry both: ```ruby render json: { errors: @booking.errors.details, messages: @booking.errors.full_messages }, status: :unprocessable_content ``` Keep the shape identical across endpoints. A small private helper in `Api::V1::BaseController` (for example `render_validation_errors(record)`) stops each controller inventing its own. How the body should look in general (error codes, problem details, correlation ids) is a design question other topics cover; the Rails part is getting these shapes out of `errors`. ## The status symbol HTTP 422 is the status for a well-formed request whose content failed validation. Rails accepts it as a symbol: 1. **`:unprocessable_content`** is the current name, defined by Rack 3.1 and later; Rails 8.1's generators write it. 2. **`:unprocessable_entity`** is Rack's obsolete name for the same code. It still maps to 422 but prints a deprecation warning on Rack 3.2. 3. The integer `422` always works. Status symbols are looked up in Rack's table, so a typo raises an error rather than silently sending 200. ## Errors that are not validation failures - `create!`/`save!` raise **`ActiveRecord::RecordInvalid`** instead of returning `false`; its `record` attribute gives you the same `errors`. Catching it with `rescue_from` lets one handler render the body for every action. - `ActiveRecord::RecordNotFound` from `find` should become a 404 with a small JSON body, not a validation shape. Both are commonly mapped in the version's base controller so every endpoint answers errors the same way. ## What not to send `errors` contains only messages, codes and validator options. Avoid adding exception messages, backtraces or SQL to the body. For uniqueness failures, `details` reports `{ error: :taken, value: ... }`, which echoes the submitted value; strip `value` if it could reveal another customer's data, such as an email address. ## Testing the error contract Pin the shape and the status together, since a client depends on both: ```ruby post api_v1_bookings_path, params: { booking: { passenger_name: "" } }, as: :json assert_response :unprocessable_content assert_equal [{ "error" => "blank" }], response.parsed_body.dig("errors", "passenger_name") ``` `assert_response` accepts the same status symbols as `render`, so the test reads like the controller. Asserting on the code (`"blank"`) rather than the English sentence keeps the test stable when someone rewords or translates the message.
- Why might errors.details expose more than you intended?Some validators record the rejected value in the details hash, for example `{ error: :taken, value: "[email protected]" }` from a uniqueness check, or the value for format. Echoing it back is harmless for the submitter's own input but can confirm that another account exists. Map details to codes only, dropping `value`, when the field identifies people.
- How do you produce the same body when using save! instead of save?`save!` raises `ActiveRecord::RecordInvalid`. Add `rescue_from ActiveRecord::RecordInvalid, with: :render_invalid` in the base controller, and in the handler call `exception.record.errors.details` and `full_messages`, rendering with `status: :unprocessable_content`. Every action then shares one error path.
- render json: record.errors sends a flat array of full sentences.
- :unprocessable_entity is the current Rails 8.1 name for 422.
- errors.full_messages gives codes a mobile client can switch on.
- A failed save should still answer 200 with an errors key.
- errors.details returns only English message strings.
Assumes Rails 8.1 on Rack 3.1 or later, where :unprocessable_content is the 422 symbol; :unprocessable_entity is Rack's obsolete name and warns on Rack 3.2.