Handling multi-format responses
This course covers how a Rails controller action sends back different responses depending on the format a request resolves to. It starts with respond_to in the app's 404 handler. Then it reads Rails' installed source to show the order used to pick a format: the format parameter, the Accept header and the HTML default. Later lessons cover the no-block shorthand, format.any and its alias format.all, branching on success and failure inside a format block, and a route that forces PNG with defaults.
What you'll learn
- ✓How respond_to runs only the block matching the resolved format
- ✓The order Rails follows to choose a request's format
- ✓When a format call needs a block and when the shorthand is enough
- ✓How format.any and format.all catch unclaimed formats
- ✓Branching on success and failure inside a format block
- ✓Forcing a format at the route with defaults: { format: :png }
respond_to do |format|...end, already running in this app's 404 handler
Nested resource routing, the course before this one, traced how a request reaches a controller action. That's half the job. Once an action like Admin::Catalog::Lessons::ImagesController#destroy runs, it has to decide what to send back, and in this app there's often more than one right answer: a…
Read the full lesson free →Curriculum
7 lessonsrespond_to do |format|...end, already running in this app's 404 handler
How respond_to runs only the block matching the request's format, shown through the app's 404 handler.
How the format is chosen, in Rails' installed source
The order Rails uses to pick a format: format parameter, Accept header, path extension, XHR, then HTML.
The no-block shorthand: format.turbo_stream alone vs. a block
When format.turbo_stream alone is enough and when a block is needed to render a different template.
format.any and format.all: one catch-all, two names
How format.any catches unclaimed formats, why format.all is the same method, and when UnknownFormat is raised.
Branching on success and failure inside one format block
Branching on a service result inside format.turbo_stream while format.html redirects with a different flash message.
defaults: { format: :png }: forcing a format before negotiation
How defaults: { format: :png } on a route sets the format before negotiation, so no respond_to is needed.
Putting it together: three patterns, one decision per route
A review of three patterns in the app: respond_to with branches, a format forced by the route, and none.