Skip to content

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.

“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.”

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 chain

Three consequences worth stating out loud:

  1. A controller instance is created per request. @current_user from a before_action lives for one request. Memoising in the controller is safe; a class variable is not.
  2. render and redirect_to do not return from the method. They set the response and execution continues. Two renders in one action is a DoubleRenderError.
  3. Views can call models. Nothing stops <%= Post.count %>. Convention says the controller decides what the view needs; the view should not query.
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.

A checkout that charges a card, creates an order and sends an email belongs in neither the controller nor the model.

app/services/checkout.rb
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)
end
end
app/controllers/orders_controller.rb
def 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
end
end

The 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::Model and ActiveModel::Attributes.
  • Query object — a scope that grew conditionals. Return a relation so it still composes with includes and pagination.
  • Presenter — five computed values for one model in a view. SimpleDelegator or a plain wrapper.
app/models/concerns/publishable.rb
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?
end

included 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.

  1. Why is a controller instantiated per request, and what does that mean for instance variables?
  2. What happens if an action calls redirect_to and then continues executing?
  3. Where would you put a rule that spans three models and must be transactional?
  4. When is a concern the wrong abstraction?
  5. How do you test a service object versus a controller action?
  • “Skinny controller, fat model” is a slogan, not an architecture. Fat models become as unmaintainable as fat controllers.
  • Putting params in 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.