skip to content

Action Controller Layer

What a Rails controller action does with a request: formats, strong parameters, filters, render and redirect, sessions, cookies, streaming and rescue_from. Every Rails interview touches it.

part ofRuby on Railsread it →
on this pageshow

explore

questions

page 1 of 2

In a Rails controller, what does an action render when it never calls render or redirect_to, and how do its instance variables reach the view?

level: juniorimportance: must knowfreq 80%

answer

  1. convention over configuration
  2. controller_path plus action_name
  3. default_render runs unless performed?
  4. view_assigns copies instance variables
  5. one controller instance per request

basics

~10 s

An action that ends without rendering gets the template named after its controller and action, such as app/views/vendors/index.html.erb, and every instance variable the controller set is copied into that view; local variables are not.

solid answer

~40 s

Rails dispatches every request to a **new controller instance** and calls the public method the route names. When the method returns, `send_action` checks `performed?`; if nothing rendered, redirected or sent `head`, it calls `default_render`, which renders the template for that action in the requested format — `app/views/vendors/index.html.erb` for an HTML request to `VendorsController#index`. Before the template runs, `view_assigns` collects every instance variable on the controller, whether set in the action or in a `before_action`, minus Rails' internal ones such as `@_params`, and assigns them to the view. Locals die with the method, so `@vendors = Vendor.all` reaches the template and `vendors = Vendor.all` does not. An action can be an empty method, and if a template exists the method can even be missing.

code

ruby · 13 lines
ruby
class VendorsController < ApplicationController
  before_action :set_market

  def index
    @vendors = @market.vendors.order(:stall_number)
    open_count = @vendors.where(open: true).count # local: never reaches the view
  end

  private
    def set_market
      @market = Market.find(params.expect(:market_id))
    end
end

go deeper

for a junior

Know the path convention, controller folder plus action name plus format, and say plainly that instance variables reach the template while locals do not.

for a middle

Explain the mechanism: send_action checks performed?, default_render renders the action's template, and view_assigns copies the controller's instance variables minus Rails' protected ones.

for a senior

Point out the per-request controller instance and what really persists between requests, and spot code that leans on dozens of instance variables where a presenter or explicit locals would be clearer.

for a principal

Weigh the convention's payoff, almost no rendering code, against its cost: implicit data flow from controller to view that a team must keep readable through naming discipline and review.

## The convention Rails names things so that most actions need no rendering code at all. A **controller** is a class such as `VendorsController < ApplicationController`; an **action** is one of its public methods, such as `index`; a **template** is a file under `app/views` named after the controller path and the action, plus the format and the template handler: `app/views/vendors/index.html.erb`. When the action does not say what to send back, Rails renders that template. This is the **implicit render**, and it is why a scaffolded `show` action is an empty method. ## What happens after the action method returns 1. The router maps the request to a controller and an action name. 2. `ActionController::Metal.dispatch` builds a **new instance** of the controller for this one request. 3. The `before_action` and `around_action` callbacks run, then `send_action` calls the action method. 4. `ActionController::BasicImplicitRender#send_action` checks `performed?` — true once `render`, `redirect_to`, `head` or a send method has set a response body. 5. If nothing was performed, `default_render` runs. In a full `ActionController::Base` controller it renders the template for `action_name` in the request's format and variant. 6. Rendering builds a view context and hands it the controller's instance variables. The template lookup itself — prefixes, partials, layouts and variants on disk — is the view layer's business; the controller only decides that the action's own template is what gets rendered. ## How instance variables travel to the view - `AbstractController::Rendering#view_assigns` reads `instance_variables` on the controller, removes the protected internal ones (`@_params`, `@_response`, `@_request`, `@_action_name` and similar), and builds a hash of the rest. - The view context receives that hash and sets each entry as an instance variable of its own, so `@vendors` in the controller is `@vendors` in ERB. - The **objects are shared, not copied**: mutating `@vendors` in the template mutates the same relation, but reassigning `@vendors` in the template does not change the controller's variable. - Instance variables set in a `before_action`, such as a `set_market` loader, arrive too, because callbacks and the action run on the same instance. - **Local variables never arrive.** They belong to the method's scope and are gone when it returns. - Nothing leaks between requests: the instance is thrown away after the response, so `@vendors` from one request cannot appear in the next. Class-level state is a different story and is shared by every request in the process. ## Edge cases | Situation | What Rails sends | |---|---| | Empty `def show; end` and `show.html.erb` exists | The template, with any variables set by callbacks | | No `show` method at all, but `show.html.erb` exists | The template: `ImplicitRender#method_for_action` treats a template as an action | | The action calls `render` or `redirect_to` itself | Whatever it asked for; the implicit render is skipped because `performed?` is true | | No template for the request at all | A 406 or an empty 204, depending on the request — a separate set of rules | ## Why interviewers start here The question looks simple, but the answer shows whether a candidate has a working model of a request. Three facts carry most of the weight: - **The method is not the response.** The action's return value is ignored; what matters is whether something set the response before the method returned. - **The template is chosen by convention, not by the action.** Controller path, action name and the request's format pick the file, so renaming an action without renaming its template breaks the page. - **State is per request.** The controller is a short-lived object, which is why instance variables are a safe hand-off to the view and an unsafe cache. A candidate who can say those three things can usually reason through the follow-ups — missing templates, multiple formats, shared helpers — without having memorised them. ## A worked example A farmers-market vendor list sets two instance variables and one local. Only the two instance variables are visible in `app/views/vendors/index.html.erb`; `open_count` is computed and discarded. ## Common mistakes - Expecting a local to show up in the template, then "fixing" it with a global or a constant. - Believing the controller object survives between requests and caching per-user data in an instance variable "for next time". - Calling `render :index` at the end of `index` out of habit. It works, but it repeats what the convention already does and hides the cases where a different template really is rendered. - Assigning dozens of instance variables. Every one becomes view state; a template that needs many is usually asking for a presenter object or a partial with explicit locals. Knowing exactly when the implicit render fires also explains its failures: when no template matches, the same `default_render` method decides between an error and an empty response.

  • What happens if a route points at a Rails action that has a template but no method in the controller?
    The request still succeeds. `ImplicitRender#method_for_action` falls back to `default_render` when a template exists for the action name, so Rails renders that template. Callbacks still run, so instance variables set in a `before_action` are available, but there is no action body to set anything else.
  • Why can an instance variable from one Rails request never show up in the next request's view?
    `ActionController::Metal.dispatch` calls `new` for every request, so each request has its own controller object and its own instance variables, which are discarded with the object. Data that does persist across requests lives elsewhere: the session, the cache, the database, or class-level state, which is shared by every request in the process and is a common source of leaks.
  • Does a Rails view get a copy of the controller's objects or the same objects?
    The same objects. `view_assigns` builds a hash of names to the controller's objects and the view sets them as its own instance variables. Calling a mutating method on `@vendors` in the template affects that object, but assigning a new value to `@vendors` in the template only changes the view's variable.

  • An action must end with an explicit render call or the browser gets a blank page.
  • Local variables in the action are visible in the template just like instance variables.
  • The controller object is reused across requests, so instance variables persist between them.
  • Instance variables set in a before_action do not reach the view; only the action's do.
  • A route to an action without a controller method always fails, even when the template exists.
open as a page

In a Rails controller, what does before_action :set_bouquet, only: %i[show edit update destroy] do, and why do scaffolds generate it?

level: juniorimportance: must knowfreq 82%

basics

~20 s

It runs the private set_bouquet method before show, edit, update and destroy, so each starts with @bouquet already loaded from the id in the URL; scaffolds generate it so the lookup is written once instead of four times.

open as a page

In a Rails 8.1 app in production, why does Track.find with an id that does not exist show a 404 page instead of a 500?

level: juniorimportance: must knowfreq 62%

basics

~10 s

Track.find raises ActiveRecord::RecordNotFound, which Active Record maps to :not_found in config.action_dispatch.rescue_responses. In production the ShowExceptions middleware turns the unhandled exception into a 404 and serves public/404.html.

open as a page

In a Rails controller, what happens if you pass params[:job_application] straight to JobApplication.new, and how do strong parameters fix it?

level: juniorimportance: must knowfreq 82%

basics

~10 s

params[:job_application] is an unpermitted ActionController::Parameters, so Active Record raises ActiveModel::ForbiddenAttributesError. Strong parameters fix it with an allow-list, params.expect(job_application: [...]), which returns a permitted copy holding only the listed keys.

open as a page

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%

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.

open as a page

In a Rails controller, when do you use send_file versus send_data, and what do their disposition:, type: and filename: options control?

level: juniorimportance: must knowfreq 55%

basics

~20 s

send_file serves a file that already exists on disk by its path; send_data sends a String of bytes built in memory. Both default to an attachment download, guess the type from filename's extension and fall back to application/octet-stream.

open as a page

In a Rails controller, how does respond_to pick between format.html, format.json and format.csv, and what happens for a format it does not list?

level: middleimportance: must knowfreq 62%

basics

~20 s

respond_to registers the formats the action serves, then picks the first of request.formats that it lists; a block-less format line renders the matching template, and a format it does not list raises ActionController::UnknownFormat, a 406.

open as a page

In a Rails controller, how does a before_action stop the action from running, and why does returning false from it change nothing?

level: middleimportance: must knowfreq 70%

basics

~20 s

A before_action halts the chain by rendering, redirecting or sending head: after each callback Rails checks performed?, and once a response exists the remaining callbacks and the action are skipped. Return values are ignored, so false does nothing.

open as a page

In a Rails controller, how do cookies.signed and cookies.encrypted differ, and which fits a remember-me token versus a dismissed-banner flag?

level: middleimportance: must knowfreq 60%

basics

~20 s

cookies.signed adds an HMAC so the client can read but not change the value; cookies.encrypted also hides it with AES-256-GCM. Both return nil for a tampered value. A remember-me token goes in a signed or encrypted jar; a dismissed-banner flag can be a plain cookie.

open as a page

In a Rails controller, how do rescue_from handlers declared with with: or a block work, and which runs when several match?

level: middleimportance: must knowfreq 55%

basics

~20 s

rescue_from registers a method (with:) or a block for exception classes raised in a controller's callbacks, action or rendering. Rails checks handlers from the last declared upward, subclass before parent, and runs the first whose class matches.

open as a page

In Rails 8, why does params.expect replace params.require(...).permit(...), and how does each handle a tampered job_application parameter?

level: middleimportance: must knowfreq 66%

basics

~20 s

params.expect requires and permits in one type-strict call: a job_application sent as a string or the wrong shape raises ParameterMissing, answered 400, while require(...).permit(...) can crash with NoMethodError (500) or accept a hash where an array was meant.

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, when do you use flash.now instead of flash, and what do flash.keep and add_flash_types add?

level: middleimportance: must knowfreq 65%

basics

~20 s

flash[:notice] is shown on the next request, so it pairs with redirect_to; flash.now[:alert] is shown only in the current request, so it pairs with render. flash.keep carries entries through one more request, and add_flash_types adds keys usable like notice: and alert:.

open as a page

What does allow_browser versions: :modern in a generated Rails 8.1 ApplicationController do, and which requests does it still let through?

level: middleimportance: should knowfreq 35%

basics

~20 s

allow_browser adds a before_action that renders public/406-unsupported-browser.html with 406 to browsers older than Safari 17.2, Chrome 120, Firefox 121 or Opera 106, and to Internet Explorer; unknown agents, bots and requests without a version pass.

open as a page

In a Rails ApplicationController, why do shared methods like current_market belong under private, and what does helper_method add?

level: middleimportance: should knowfreq 45%

basics

~10 s

Every public method of a Rails controller, including those inherited from ApplicationController, counts as an action, so shared code goes under private; helper_method :current_market then lets views call that private method through the controller.

open as a page

In Rails, in what order do inherited before_action callbacks run, and how do prepend_before_action and skip_before_action change that chain?

level: middleimportance: should knowfreq 50%

basics

~20 s

A subclass inherits its parent's callback chain and appends its own, so ApplicationController's callbacks run first; prepend_before_action inserts at the front, and skip_before_action removes a named callback, or narrows it with only:, raising ArgumentError if it is not in the chain.

open as a page

In Rails 8.1, how do config.action_dispatch.show_exceptions and config.consider_all_requests_local together decide what a request that raises receives?

level: middleimportance: should knowfreq 38%

basics

~10 s

show_exceptions decides whether Rails renders a response for an exception (:all, :rescuable for mapped classes only, :none); consider_all_requests_local decides whether that response is the detailed debug page or the public error page.

open as a page

With Rails 8 strong parameters, how do you permit a job application's nested address, an array of skill names and a list of references?

level: middleimportance: should knowfreq 55%

basics

~10 s

Inside params.expect, name scalar keys directly, a nested hash as address_attributes: [:street, :city], scalar arrays as skill_names: [], and arrays of hashes with double brackets, references_attributes: [[:id, :name, :_destroy]]; anything else is dropped.

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, how do you push a CI build's log lines to the browser as they arrive with ActionController::Live and Live::SSE?

level: middleimportance: should knowfreq 38%

basics

~10 s

Include ActionController::Live, set Content-Type to text/event-stream, wrap response.stream in ActionController::Live::SSE and write each log line as an event; the first write commits the headers, and the stream must be closed in an ensure.

open as a page

In Rails 8.1, what does setting config.action_dispatch.x_sendfile_header change about how send_file delivers a file?

level: middleimportance: should knowfreq 30%

basics

~20 s

x_sendfile_header tells Rack::Sendfile which header the front server understands. send_file's body responds to to_path, so the middleware drops the body and sends only that header; the front server then reads and sends the file instead of Ruby.

open as a page

In a Rails controller, when an action does not render and no template matches the request, when does the client get a 406 and when an empty 204?

level: seniorimportance: should knowfreq 32%

basics

~20 s

If the action has templates for other formats, Rails raises UnknownFormat (406); if it has none and the request is a non-XHR browser GET for HTML, MissingExactTemplate (406); any other request silently gets 204 No Content.

open as a page

In a Rails controller, what goes wrong when an around_action forgets to yield or the action raises, and how do after_action callbacks behave in those cases?

level: seniorimportance: should knowfreq 38%

basics

~20 s

An around_action that never yields silently skips the action, later callbacks and after_action callbacks, with no error. If the action raises, after_action callbacks do not run and code after yield is skipped unless it sits in an ensure block.

open as a page

In Rails, how does config.action_dispatch.cookies_rotations keep signed and encrypted cookies readable after you change the secret, cipher or digest?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Each cookies.rotate entry gives the signed or encrypted jar an extra secret, digest or cipher to try when the current one fails. Cookies are always written with the current settings, and a cookie read through an old entry is re-written with the current key, so the rotation can be removed later.

open as a page

In Rails 8.1, what stops a signed remember-me cookie from being replayed after its expiry or pasted into a different cookie name?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Metadata inside the signed value. With load_defaults 6.0 or later, including 8.1, the signed and encrypted jars embed the expires: time and a purpose of cookie.<name>, so Rails returns nil for an expired value or one copied into another cookie, whatever the browser sends.

open as a page

How do you serve dynamic error pages with the app's layout in Rails 8.1 through config.exceptions_app, and what must that error app avoid?

level: seniorimportance: should knowfreq 28%

basics

~20 s

Set config.exceptions_app to the app's routes (or any Rack app); ShowExceptions then sends GET /404, /500 and so on to an errors controller. It must set the status explicitly, cover every status, and never raise, or Rails falls back to a plain-text 500.

open as a page

In Rails, when would you map an exception in config.action_dispatch.rescue_responses instead of handling it with rescue_from?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Map it in rescue_responses when a status and the standard error page are enough everywhere; use rescue_from when the response needs controller work such as a redirect, a flash or a layout. Mappings match the exact class name, while rescue_from matches subclasses.

open as a page

showing 1–30 of 38