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.
The 60-second answer
Section titled “The 60-second answer”“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.”
Actions
Section titled “Actions”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: []) endendThree details interviewers look for:
render :newmust sendstatus: :unprocessable_entity(422). Turbo needs a non-2xx status for a failed form; without it the form appears to succeed.redirect_toafterDELETEshould usestatus: :see_other(303), or some clients repeat theDELETE.current_user.posts.findscopes the lookup, so another user’s post is a 404 rather than a check someone forgot.
Filters and strong parameters
Section titled “Filters and strong parameters”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.
Sessions, cookies and flash
Section titled “Sessions, cookies and flash”session[:user_id] = user.idreset_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 redirectflash.now[:alert] = "Invalid." # for this render onlyThe 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.
Layouts and rendering
Section titled “Layouts and rendering”render :show # posts/show.html.erbrender "shared/nav" # shared/_nav.html.erbrender partial: "post", collection: @posts, as: :post # once per postlayout 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.
Partials, helpers, components
Section titled “Partials, helpers, components”<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) %>Escaping
Section titled “Escaping”<%= 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.
Follow-up questions
Section titled “Follow-up questions”- Why does
rendernot stop execution, and what error results from rendering twice? - What is the difference between
flashandflash.now? - Why is
skip_before_action :verify_authenticity_tokendangerous? - Where does a Rails session live by default, and what can you not store in it?
Common traps
Section titled “Common traps”render :newwithout 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_safeon user input. The most common Rails XSS.