Skip to content

Controllers and Views

A controller is an object whose lifetime is one request; a view is a method call that returns a string. Everything else — filters, helpers, partials, components — is organisation on top of those two facts.

“A controller action is a public instance method; everything else should be private or a filter. before_action is how you authenticate, authorise and load records, and skip_before_action is where authorisation holes come from. Incoming data is never trusted: params is an ActionController::Parameters, and require/permit produce strong parameters — without them create raises ForbiddenAttributesError. Sessions live in an encrypted cookie by default; flash is a session slice that survives exactly one redirect. The view is ERB compiled to Ruby, so <%= %> escapes by default — raw, html_safe and <%== are the opt-outs, and each is an XSS risk. Layouts wrap pages, partials extract fragments, helpers keep formatting out of templates, and view components do it with a class.”

app/controllers/posts_controller.rb
class PostsController < ApplicationController
before_action :authenticate_user!
before_action :set_post, only: [:show, :edit, :update, :destroy]
def index
@posts = Post.published.recent.page(params[:page])
end
def create
@post = current_user.posts.build(post_params)
if @post.save
redirect_to @post, notice: "Post created."
else
render :new, status: :unprocessable_entity
end
end
private
@post = current_user.posts.find(params[:id])
end
def post_params
params.require(:post).permit(:title, :body, tag_ids: [])
end
end

Three details interviewers look for:

  • render :new must send status: :unprocessable_entity (422). Turbo needs a non-2xx status for a failed form; without it the form appears to succeed.
  • redirect_to after DELETE should use status: :see_other (303), or some clients repeat the DELETE.
  • current_user.posts.find scopes the lookup, so another user’s post is a 404 rather than a check someone forgot.

Filters are declared with before_action, around_action and after_action, and take only:/except: so a group of actions shares one authentication or lookup step.

params.require(:post).permit(:title, :body, tag_ids: []) is an allow-list: unnamed keys are dropped, not rejected, so a typo’d field silently does nothing. Nested attributes need _attributes and accepts_nested_attributes_for. permit! and to_unsafe_h disable the protection entirely, and passing params to where is injectable through the keys.

session[:user_id] = user.id
reset_session # on login, to prevent session fixation
cookies.encrypted[:remember] = {
value: user.signed_id(purpose: :remember, expires_in: 30.days),
httponly: true, secure: true, same_site: :lax, expires: 30.days
}
flash[:notice] = "Saved." # survives the next redirect
flash.now[:alert] = "Invalid." # for this render only

The default session store is an encrypted, client-side cookie: keep it small. cookies.signed is tamper-evident but readable; cookies.encrypted is both. A cookie-only session cannot be revoked, which is why Rails 8’s authentication generator adds a database session record.

render :show # posts/show.html.erb
render "shared/nav" # shared/_nav.html.erb
render partial: "post", collection: @posts, as: :post # once per post

layout false disables the layout for an action; Turbo Frame requests do not need it, since Turbo handles frames automatically. The layout itself lives in app/views/layouts/application.html.erb, wraps every action’s output in <%= yield %>, and is the one place for <head> tags, CSRF meta tags and navigation.

app/views/posts/_post.html.erb
<article id="<%= dom_id(post) %>">
<h2><%= link_to post.title, post %></h2>
<p><%= truncate(post.body, length: 160) %></p>
</article>

dom_id(post) gives post_42 — the id Turbo Streams target, so use it instead of hand-written ids. Helpers are global to every view (a helper named title collides eventually) and a helper that queries runs per render. For anything with real logic, a ViewComponent class has state, tests and its own template:

class AlertComponent < ViewComponent::Base
def initialize(message:, level: :info)
@message, @level = message, level
end
private
def classes = "alert alert--#{level}"
end
<%= render AlertComponent.new(message: "Saved.", level: :success) %>
<%= user.name %> <%# HTML-escaped automatically %>
<%== user.bio %> <%# NOT escaped — same as raw %>
<%= raw(user.bio) %> <%# NOT escaped %>
<%= sanitize(user.bio, tags: %w[b i em strong]) %>

ERB output is escaped unless the string is html_safe. raw, html_safe, <%== and an over-permissive sanitize are the four ways XSS enters a Rails app. Inside an attribute, quote it; inside a <script> tag, ERB escaping does not help — pass the value through a data- attribute instead.

  1. Why does render not stop execution, and what error results from rendering twice?
  2. What is the difference between flash and flash.now?
  3. Why is skip_before_action :verify_authenticity_token dangerous?
  4. Where does a Rails session live by default, and what can you not store in it?
  • render :new without a status. Turbo treats 200 as success and the form looks broken.
  • Authorisation in the view. Hiding a button is not access control; the action must check.
  • html_safe on user input. The most common Rails XSS.