skip to content

Render, Redirect & Head

An action answers once: render a template, text or body, redirect_to with a status, or head with no body. Interviewers ask about 302 vs 303, redirect_back_or_to and what raises DoubleRenderError.

part ofRuby on Railsread it →
on this pageshow

explore

questions

6

In a Rails controller, how does render :show differ from redirect_to @ticket at the end of a ticket update action?

level: juniorimportance: must knowfreq 80%

answer

  1. one request or two
  2. render :action runs no action code
  3. 3xx status plus Location header
  4. refresh re-sends the form
  5. neither call ends the method

basics

~20 s

render :show builds the show template inside the same PATCH request, using update's instance variables and running none of show's code. redirect_to @ticket answers with a 3xx and a Location header, so the browser sends a new GET that runs the show action.

solid answer

~40 s

`render :show` is a template choice, not a call to the `show` method: Rails renders `tickets/show.html.erb` with whatever instance variables `update` set, inside the current PATCH request, and the address bar still holds the URL the form was sent to. `redirect_to @ticket` builds the URL with `url_for`, sets the `Location` header and a 3xx status (302 unless you pass `status:`) with an empty body; the browser then sends a fresh GET, which runs `show` and its `before_action` filters from scratch. After a successful write you redirect, so a refresh repeats a harmless GET instead of the form submission and the flash message travels to the next page. Neither call returns from the action: code after them still runs.

code

ruby · 14 lines
ruby
class TicketsController < ApplicationController
  before_action :set_ticket

  def show
    @comments = @ticket.comments.order(:created_at)
  end

  def update
    if @ticket.update(ticket_params)
      redirect_to @ticket, notice: "Ticket updated.", status: :see_other
    end
    # render :show here would run without @comments
  end
end

go deeper

for a junior

Recall that render picks a template for this request while redirect_to tells the browser to make a new GET. Know that render :show does not run show.

for a middle

Explain the Location header and 3xx status, which instance variables the template sees, and why a refresh re-submits a rendered PATCH response but repeats a GET after a redirect.

for a senior

Show you choose per outcome: redirect after successful writes, render when the answer belongs to this request, and spot templates that rely on ivars only the other action sets.

for a principal

Frame Post/Redirect/Get as a team convention backed by the scaffold, and weigh the extra round trip of a redirect against safe refreshes, clean history and bookmarkable URLs.

## Two different answers to one request A helpdesk app has a `TicketsController` with the usual resourceful actions. An agent edits ticket 42 and submits the form, which arrives as `PATCH /tickets/42` and runs `update`. Once the ticket is saved, the action has to answer that request, and Rails gives it two broad ways to do so: - **`render`** produces a response body now, from a template, in this request. - **`redirect_to`** produces no page at all: it answers with a **redirect status** and a `Location` header, and the browser makes a **second request** to that URL. Interviewers ask the difference because each one changes who runs which code, what the address bar shows and what a refresh does. ## What `render :show` actually does `render :show` (the same as `render action: :show` or `render "show"`) tells Action View which **template** to use. It does **not** call the `show` method. The view `tickets/show.html.erb` is rendered with the instance variables the **current** action assigned, so: 1. `@ticket` is available because `update` (or its `set_ticket` filter) set it. 2. Anything `show` would normally load, such as `@comments = @ticket.comments.recent`, is **missing** unless `update` also loads it. The template then fails on `nil` or quietly shows an empty list. 3. The response goes back to the PATCH request. The browser shows the page under the URL the form was sent to, and pressing refresh asks to **re-submit the form**. `render "tickets/show"` or `render template: "tickets/show"` pick a template by path, which is how one controller renders another controller's view; the rules above still apply. A `render` call with no layout option uses the controller's layout, exactly as an implicit render would. ## What `redirect_to @ticket` actually does `redirect_to` converts its argument into a URL (`url_for(@ticket)` gives `/tickets/42`), sets the `Location` header, sets the status and stores an **empty body**: ```ruby def update if @ticket.update(ticket_params) redirect_to @ticket, notice: "Ticket updated.", status: :see_other else # the failed-save branch is a separate topic end end ``` The browser follows the `Location` header with a **GET** request. That second request runs the full stack again: routing, `show`'s `before_action` filters, the `show` method and its implicit render. The `notice:` option stores a flash message that survives exactly into that next request. By default `redirect_to` answers **302 Found**; the scaffold passes `status: :see_other` (303) on update and destroy. ## Side by side | | `render :show` | `redirect_to @ticket` | |---|---|---| | HTTP status | 200 unless `status:` is given | 302 unless `status:` is given | | Requests | one | two (the original plus a GET) | | Runs `show` method | no | yes, in the second request | | Address bar | the URL the form was sent to | `/tickets/42` | | Refresh | re-submits the form | repeats a GET | | Instance variables | the current action's | whatever `show` sets | ## Why successful writes redirect The convention is **Post/Redirect/Get**: after any successful create, update or destroy, answer with a redirect. It keeps the browser history clean, makes refresh safe, lets bookmarks point at a real resource URL and gives the flash a request to appear in. Rendering is for answers that belong to the current request, such as showing the same form again, a search result, or a page assembled from data you already loaded. ## Mistakes interviewers listen for - **"render :show calls show."** It only selects the template; no action code runs. - **"redirect_to returns from the action."** Both calls only set the response. Code after them runs, and a second `render` or `redirect_to` raises `AbstractController::DoubleRenderError`. - **"redirect skips filters."** The redirected GET is a normal request, so every `before_action` on `show` runs. - **"render keeps the URL in sync."** The URL stays whatever the browser requested; rendering never changes it.

  • If an update action redirects, how does a success message reach the next page?
    Pass `notice:` or `alert:` to `redirect_to` (or set `flash[:notice]` first). The flash is stored in the session and is readable during the very next request, which is the GET the browser makes to the `Location` URL, after which it is discarded.
  • When is rendering a different action's template the right answer?
    When the response belongs to the current request and you already hold its data: re-showing a form with the submitted values, a filtered list built in this action, or a confirmation page that must not be bookmarked. You must then set every instance variable that template reads, because the other action's method does not run.

render is a clerk handing you the finished document at the counter you queued at; redirect_to is the clerk handing you a slip that says 'go to counter 42', where you queue again and that counter does its own work before giving you anything.

  • render :show runs the show method and then renders its view
  • redirect_to returns from the action, so later code never runs
  • redirect_to skips the show action's before_action filters
  • render :show changes the browser's URL to the show page
  • redirect_to forwards the request internally without a second HTTP request
open as a page

In Rails, why does the scaffold's update action pass status: :see_other to redirect_to instead of keeping redirect_to's default status?

level: middleimportance: must knowfreq 60%

basics

~20 s

redirect_to answers 302 Found by default, and a client that sent a real PATCH or DELETE may repeat that method when following a 302. 303 See Other tells every client to follow with GET, so the scaffold uses status: :see_other on update and destroy.

open as a page

In a Rails controller, what does head :no_content send, and when should an action answer with head instead of render?

level: middleimportance: should knowfreq 45%

basics

~20 s

head :no_content sends a 204 status, the headers you pass and an empty body, with no Content-Type. Use head when the status and headers are the whole answer: webhook acknowledgements, script calls that need no markup, or refusals like :forbidden.

open as a page

In Rails 8.1, what does redirect_back_or_to do when the request has no Referer header or one pointing at another host?

level: middleimportance: should knowfreq 40%

basics

~20 s

It redirects to the fallback location given as its first argument. redirect_back_or_to uses request.referer only when the header exists and its host is allowed; with load_defaults 8.1 a Referer from another host is not allowed, so the fallback wins.

open as a page

In a Rails controller, why does an update action that calls a private guard method doing redirect_to ... and return still raise AbstractController::DoubleRenderError?

level: seniorimportance: should knowfreq 50%

basics

~20 s

The return inside the guard exits only the guard method. The action keeps running to its own redirect_to or render, which finds response_body already set and raises AbstractController::DoubleRenderError. Check performed? after the guard, or make the guard a before_action.

open as a page

In a Rails controller, what do render's template:, plain:, html:, body: and inline: options each send, and which of them use the layout?

level: juniorimportance: nice to knowfreq 25%

basics

~20 s

template: renders a view file by path inside the layout; plain: sends text/plain; html: sends text/html, escaping strings not marked html_safe; body: sends the string as is, text/plain unless content_type: says otherwise; inline: renders an ERB string. Only template renders get the layout unless layout: is passed.

open as a page