MVC in Rails
MVC in Rails is not a diagram on a slide; it is a fixed path every request walks. Knowing the path explains most of the framework’s behaviour: why instance variables reach the view, why render twice raises, why before_action can be skipped, why a fat model is still a problem.
The 60-second answer
Section titled “The 60-second answer”“A request hits Rack, then ActionDispatch::Routing matches it to posts#show with params. Rails instantiates PostsController, runs the before_action chain, calls show, which loads @post = Post.find(params[:id]). If the action does not call render or redirect_to, Rails renders app/views/posts/show.html.erb inside layouts/application, copies every instance variable into the view context, and returns the body through the middleware stack. The model owns data and invariants, the controller owns HTTP and orchestration, the view owns presentation. Business logic that belongs to neither goes in a plain Ruby object — a service, form or query object — not in the controller.”
The lifecycle
Section titled “The lifecycle”Rack middleware (logging, cookies, session, CSRF, params parsing) → routes.rb matches verb + path → PostsController#show, params = {...} → controller instantiated per request (no state survives between requests) → before_action callbacks (auth, load resource, set locale) → action method → model layer (queries, validations) → instance variables → after_action, then implicit or explicit render → template + layout + helpers → HTML → back up the middleware chainThree consequences worth stating out loud:
- A controller instance is created per request.
@current_userfrom abefore_actionlives for one request. Memoising in the controller is safe; a class variable is not. renderandredirect_todo not return from the method. They set the response and execution continues. Two renders in one action is aDoubleRenderError.- Views can call models. Nothing stops
<%= Post.count %>. Convention says the controller decides what the view needs; the view should not query.
Who owns what
Section titled “Who owns what”| Layer | Owns | Must not own |
|---|---|---|
| Model | Data, invariants, associations, scopes | HTTP, cookies, params, rendering |
| Controller | HTTP concerns, authorisation, orchestration | Multi-step business rules, SQL |
| View | Presentation, formatting, escaping | Queries, business rules, writes |
| Service / form / query object | One use case, one transaction | Request state |
The failure mode is not “fat model” or “fat controller” — it is logic with no name. A 40-line create action is a missing object. A 600-line model is six of them.
Where the logic goes
Section titled “Where the logic goes”A checkout that charges a card, creates an order and sends an email belongs in neither the controller nor the model.
class Checkout Result = Data.define(:success, :order, :error)
def initialize(cart:, user:, gateway: PaymentGateway.new) @cart, @user, @gateway = cart, user, gateway end
def call Order.transaction do order = Order.create!(user: @user, line_items: @cart.to_line_items) charge = @gateway.charge(amount: order.total_cents, token: @cart.payment_token) order.update!(paid_at: Time.current, payment_reference: charge.id) OrderMailer.confirmation(order).deliver_later Result.new(success: true, order: order, error: nil) end rescue PaymentGateway::Declined => e Result.new(success: false, order: nil, error: e.message) endenddef create result = Checkout.new(cart: current_cart, user: current_user).call
if result.success redirect_to result.order, notice: "Order placed." else flash.now[:alert] = result.error render :new, status: :unprocessable_entity endendThe action is now four lines of HTTP. The use case is testable without a request, and the gateway can be swapped in a test without stubbing constants.
- Form object — one form writing to several models, or validation about the form rather than a
row. Use
ActiveModel::ModelandActiveModel::Attributes. - Query object — a scope that grew conditionals. Return a relation so it still composes with
includesand pagination. - Presenter — five computed values for one model in a view.
SimpleDelegatoror a plain wrapper.
Concerns, done properly
Section titled “Concerns, done properly”module Publishable extend ActiveSupport::Concern
included do scope :published, -> { where.not(published_at: nil) } scope :draft, -> { where(published_at: nil) } validates :published_at, presence: true, if: :published? end
def publish! = update!(published_at: Time.current) def published? = published_at.present?endincluded do ... end runs in the including class’s context, which is how scope and validates reach the model. class_methods do ... end declares class-level methods.
Follow-up questions
Section titled “Follow-up questions”- Why is a controller instantiated per request, and what does that mean for instance variables?
- What happens if an action calls
redirect_toand then continues executing? - Where would you put a rule that spans three models and must be transactional?
- When is a concern the wrong abstraction?
- How do you test a service object versus a controller action?
Common traps
Section titled “Common traps”- “Skinny controller, fat model” is a slogan, not an architecture. Fat models become as unmaintainable as fat controllers.
- Putting
paramsin a model. The model can then only be used through a request. - Private controller methods as business logic. No reuse, no isolation, untestable without HTTP.
skip_before_action :authenticate_user!. A common source of authorisation holes; prefer an explicit allow-list to a skip.- Helpers that query. A helper calling
Post.where(...)runs per render and is invisible in the controller’s query log.