skip to content

In Rails, how does Action View turn ProfilesController#show into a template file, and what does each part of show.html.erb mean?

level: middleimportance: should knowfreq 42%

answer

  1. view paths times prefixes
  2. name.locale.format+variant.handler
  3. inherited prefixes reach application/
  4. format outranks locale, variant, handler
  5. ActionView::MissingTemplate lists what it searched

basics

~20 s

Rails' Action View searches each view path, app/views first, under the controller's prefixes, such as profiles then application, for a file named after the action, filtered by locale, format, variant and handler: show.html.erb is action show, format html, handler erb.

solid answer

~30 s

Lookup has three inputs. **View paths** are the root folders, `app/views` plus any added with `prepend_view_path` or `append_view_path` and engines' view folders. **Prefixes** come from the controller and its ancestors, so `Admin::ProfilesController < ApplicationController` searches `admin/profiles` and then `application`. **Details** are the requested locale, formats, variants and handlers. A file name parses as `name[.locale][.format][+variant][.handler]`, so `show.html.erb` is action `show`, format `html`, handler `erb`. Candidates are ranked by format first, then locale, variant and handler, and a file that omits a part still matches. When a render finds nothing, `ActionView::MissingTemplate` names the prefixes, details and paths it tried.

code

ruby · 16 lines
ruby
class Admin::ProfilesController < ApplicationController
  # searched: app/views/admin/profiles/show.*, then app/views/application/show.*
  def show
    @member = Member.find(params.expect(:id))
  end
end

class ApplicationController < ActionController::Base
  before_action :use_partner_theme

  private
    def use_partner_theme
      theme = Current.partner&.theme_slug
      prepend_view_path Rails.root.join("app/themes", theme) if theme
    end
end

go deeper

for a junior

Know that app/views/<controller>/<action>.html.erb is found by convention and what the format and handler parts of the name mean.

for a middle

Explain view paths, inherited prefixes, the detail parts of a file name and how to read a MissingTemplate message.

for a senior

Use prefixes and prepend_view_path deliberately for shared and themed templates, and debug the wrong-file case with annotated output.

for a principal

Judge when view-path tricks such as per-tenant themes are worth their indirection compared with components or configuration.

## The pieces of a lookup When a Rails controller renders the `show` template, Action View's **lookup context** builds a search from three inputs. 1. **View paths**: an ordered list of root folders. A new app has `app/views`; engines contribute their own `app/views`, and a controller can call `prepend_view_path` (searched first) or `append_view_path` (searched last). 2. **Prefixes**: the folders inside each root. They start with the controller's `controller_path` and continue up its superclasses until an abstract one such as `ActionController::Base`. For `Admin::ProfilesController < ApplicationController` the prefixes are `admin/profiles`, then `application`. This is **template inheritance**: a template or partial missing from `admin/profiles` is looked up in `application/`. 3. **Details**: what the request asks for. `locale` (from I18n), `formats` (from the request, such as `:html` or `:json`), `variants` (empty unless the controller sets `request.variant`) and `handlers` (every registered template handler). ## Reading a file name Action View parses each candidate file name with one pattern, `_name.locale.format+variant.handler`, and every part except the name is optional: | File | Name | Locale | Format | Variant | Handler | |---|---|---|---|---|---| | `profiles/show.html.erb` | show | - | html | - | erb | | `profiles/show.uk.html.erb` | show | uk | html | - | erb | | `profiles/show.html+phone.erb` | show | - | html | phone | erb | | `profiles/show.json.jbuilder` | show | - | json | - | jbuilder | | `profiles/_card.html.erb` | card (partial) | - | html | - | erb | The leading underscore marks a partial. Built-in handlers are `erb`, `builder`, `raw`, `html` and `ruby`; gems register more, such as Jbuilder's `jbuilder`. ## Matching and ranking A file matches when each of its parts is either among the requested values or absent. Absence always matches, which is why `show.html.erb` serves every locale and why a file with no format at all can still be picked. Among matches, Action View sorts by: 1. the position of the file's **format** in the requested formats; 2. then its **locale**; 3. then its **variant**; 4. then its **handler**. Within each level a file that names the requested value ranks above one that omits it. The search walks **prefix by prefix, and for each prefix every view path in order**; the first prefix-and-path pair with any match wins. That is what makes `prepend_view_path` an override mechanism: a white-label theme folder prepended per request shadows `admin/profiles/show` in `app/views` only when it has its own `admin/profiles/show`, and only for the files it contains. ## When nothing matches Action View raises `ActionView::MissingTemplate`, and the message is the best debugging tool: it lists the searched names (`profiles/show, application/show`), the details hash with locale, formats, variants and handlers, and every view path. A typical mistake it reveals is a JSON request reaching an action that only has `show.html.erb`. ## A worked failure A mobile client requests `/profiles/42.json` and the controller only has `profiles/show.html.erb`. The requested formats are `[:json]`, the only candidate's format is `html`, so it does not match. If the action calls `render :show`, Action View raises `ActionView::MissingTemplate` with a message that reads, in part, `Missing template profiles/show, application/show with {locale: [:en], formats: [:json], variants: [], handlers: [:raw, :erb, :html, :builder, :ruby, :jbuilder]}`. Reading that hash tells you the fix: add `show.json.jbuilder`, or stop the JSON request reaching the action. (With implicit rendering the controller checks for a template first and answers `ActionController::UnknownFormat`, a 406, instead; that branch is the controller's.) ## Seeing which file rendered In development, the generated `config/environments/development.rb` sets `config.action_view.annotate_rendered_view_with_filenames = true`, so HTML output carries `<!-- BEGIN app/views/... -->` comments around each template and partial. It answers "which of these files actually won?" without a debugger. ## What belongs elsewhere How the controller chooses the format with `respond_to` and sets `request.variant`, and the options of `render` in a controller, are controller topics. Lookup only consumes their results: a name, prefixes and details.

  • How would you share one `_sidebar` partial across every admin controller without copying it?
    Put it where the inherited prefixes reach: if the admin controllers inherit from an `Admin::BaseController`, a partial in `app/views/admin/base/` is found from all of them, and one in `app/views/application/` is found from every controller. Rendering `"sidebar"` then resolves through the prefix chain.
  • What is the difference between `prepend_view_path` and `append_view_path`?
    Both add a root folder to the controller's view paths. A prepended path is searched before `app/views`, so its files override same-named ones; an appended path is searched after, so it only supplies templates the app lacks.

  • The template is found by the model's class name, not the controller.
  • show.html.erb is used only for the default locale, never as a fallback.
  • A namespaced controller cannot reach templates in app/views/application.
  • append_view_path lets a folder override files in app/views.
  • The .erb part of the file name is the format of the response.