skip to content

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%

answer

  1. status line and headers only
  2. options hash becomes headers
  3. location: goes through url_for
  4. no Content-Type on 204, 205, 304
  5. first argument must not be a hash

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.

solid answer

~40 s

`head(status, options = nil)` sets the status, turns the remaining options into response headers, builds `location:` through `url_for` and stores an empty body. For 1xx, 204, 205 and 304 it sends no `Content-Type`; for other codes it uses the request format (HTML by default). It counts as the action's one answer, so it raises `AbstractController::DoubleRenderError` after a render or redirect, and it raises `ArgumentError` if the first argument is a hash. Reach for it when a body adds nothing: a ticket-mark-as-read endpoint called from JavaScript (`head :no_content`), an email-provider webhook (`head :ok`), `head :created, location: @ticket`, or `head :forbidden` before any work is done.

code

ruby · 9 lines
ruby
class Tickets::ReadsController < ApplicationController
  def create
    ticket = Current.user.tickets.find(params.expect(:ticket_id))
    return head(:forbidden) if ticket.archived?

    ticket.mark_read_by!(Current.user)
    head :no_content
  end
end

go deeper

for a junior

Recall that head answers with a status and headers but no body, and that head :no_content and head :ok are the common uses.

for a middle

Explain the options-to-headers conversion, location: through url_for, which statuses skip Content-Type, and that head counts as the action's one answer.

for a senior

Show you pick head for webhooks and script endpoints, render real pages for browser navigations, and return explicitly after an early head in a longer action.

for a principal

Decide per endpoint family whether clients get bodies or status-only answers, and keep that contract consistent so callers can rely on 204 meaning success with nothing to read.

## What head is `head` is Action Controller's way of answering with **no body**. Its signature in Rails 8.1 is `head(status, options = nil)`: - **`status`** is an integer or a Rack status symbol (`:ok`, `:no_content`, `:created`, `:forbidden`, `:not_found`, `:unprocessable_content`, ...). `nil` falls back to `:ok`. - **`options`** is a hash of headers. `location:` is special: it is passed through `url_for`, so a record or route helper works. `content_type:` is also taken out and used as the content type. Every other key becomes a header, with its name capitalised word by word (`x_ticket_id:` becomes `X-Ticket-Id`). It then sets `response_body` to an empty string and returns `true`. ```ruby head :created, location: @ticket # 201, Location: /tickets/42 head :no_content # 204, no Content-Type head :ok, x_ticket_id: @ticket.id # 200 with a custom header ``` ## The details interviewers probe 1. **Content-Type depends on the code.** For 100-199, 204, 205 and 304 `head` sets **no** `Content-Type`, because those responses never carry content. For anything else it uses `content_type:` if given, else the first request format, else HTML, and it drops the charset. 2. **It is an answer like any other.** It starts with the same check as `render` and `redirect_to`: if `response_body` is set it raises `AbstractController::DoubleRenderError`. 3. **It does not stop the action.** `return head(:forbidden) unless agent_can_edit?` is the idiom when more code follows. 4. **The status is positional.** `head status: :ok` passes a hash as the status and raises `ArgumentError` ("... is not a valid value for `status`"). ## When head is the right answer | Situation | Answer | |---|---| | JavaScript marks a ticket as read and needs only success | `head :no_content` | | An email provider's webhook posts an inbound message | `head :ok` after enqueueing work | | An endpoint created a record and the client follows the URL | `head :created, location: @ticket` | | A caller lacks permission and no page should be shown | `head :forbidden` | | A request asks for a format the action does not serve | `head :not_acceptable` | In each case the **status and headers carry all the information**. Rendering an empty template or `render plain: ""` would work, but `head` states the intent, skips template lookup and avoids sending a body that a 204 must not have. ## When to render instead - A human is looking at the result: a browser navigation that answers `head :forbidden` shows the browser's blank page, so render an error page instead. - The caller needs data back, such as the updated ticket or validation messages. - A redirect is the answer, as after a form submission: use `redirect_to`, which also sets `Location` but with a 3xx status and the flash options. ## head and implicit rendering If an action ends without rendering and has no template for the request's format, Action Controller's implicit render either raises (`ActionController::UnknownFormat`, or `ActionController::MissingExactTemplate` for an interactive browser GET) or logs and falls back to answering 204. An explicit `head :no_content` makes that intent visible in the action instead of relying on the fallback. ## Checking it in a test An integration test for the mark-as-read endpoint asserts the status and the absence of content: ```ruby post ticket_read_url(@ticket) assert_response :no_content assert_empty response.body ``` `assert_response` accepts the same Rack symbols `head` does, plus the range names `:success`, `:redirect`, `:missing` and `:error`. A test that asserts only `:success` would also pass for a 200 with a body, so pin the exact code when the contract is "204, nothing to read". ## Common mistakes - **`head status: :ok`** raises because the first argument must be the status itself. - **Passing a body**: `head` has no body parameter; extra keys become headers, not content. - **Calling head after render** in a fall-through branch raises `DoubleRenderError`. - **Assuming head returns from the action**: code after it still runs unless you `return`.

  • What headers does head :created, location: @ticket set?
    Status 201, a `Location` header built by `url_for(@ticket)` (for example `http://helpdesk.example.com/tickets/42`) and, because 201 may carry content, a `Content-Type` taken from the request format, HTML by default, without a charset. The body is empty.
  • Why prefer head :no_content over render plain: "" for a successful script call?
    `head :no_content` sends 204, the code that says there is no content, and omits `Content-Type`. `render plain: ""` sends a 200 with `text/plain` and an empty body, which goes through the renderer for nothing and tells the caller less.

  • head :no_content still sends a text/html Content-Type header
  • head status: :ok is the correct way to call head
  • head can be called after render because it sends no body
  • head returns from the action, so nothing after it runs
  • head :created, location: @ticket renders the ticket in the body