Rails developers will often live by the mantra “Skinny Controller, Fat Model” when writing Rails controller code.

At first it can seem like a fairly reasonable practice. The examples in Darcy Laycock’s SitePoint article “10 Ruby on Rails Best Practices” are a great example of this. Another good example is Jamis Buck’s 2006 article “Skinny Controller, Fat Model”.

However, the name of the pattern is misleading and reinforces the noxious idea that any class should be “fat”.

In this article I will discuss ways that we can refactor Rails controllers that will not cause bloat in any models.

Skinny Controller, Fat Model

The “Skinny Controller, Fat Model” practice often results in code in controllers being moved into a model. This reduces the complexity of the controller and moves the responsibility of managing instances of the model back into the model itself. For example, if we have the following controller:

class EventsController < ApplicationController
  before_action :authenticate_user!
  after_action :verify_authorized

  def approve
    @event = Event.find(params[:id])
    @event.state = :approved
    @event.approved_at = Time.now
    @event.approved_by = current_user
    @event.save!

    redirect_to(root_path)
  end
end

The specs for the controller might look a bit like:

require 'rails_helper'

describe EventsController do
  describe 'PATCH approve' do
    subject { patch :approve, id: event.id }

    let(:event) { FactoryGirl.create(:event, approved: false) }

    context "when authenticated && authorized to approve the Event" do
      sign_in_as(:administrator)

      describe "approving the Event" do
        let(:current_time) { Time.now }

        before { Timecop.freeze(Time.local(1990)) }
        after  { Timecop.return }

        specify { expect { subject }.to change { event.reload.approved? }.to(true) }
        specify { expect { subject }.to change { event.reload.approved_by }.to(current_user) }
        specify { expect { subject }.to change { event.reload.approved_at }.to(current_time) }
      end

      it { should redirect_to(root_path) }
    end

    context "when not authenticated to approve the Event" do
      it_behaves_like "a controller action that has failed an authentication check"
    end

    context "when not authorized to approve the Event" do
      sign_in_as(:public_user)

      it_behaves_like "a controller action that has failed an authorization check"
    end
  end
end

The “Skinny Controller, Fat Model” practice might be followed by moving the approval code into the model, leaving the controller looking something like:

class EventsController < ApplicationController
  before_action :authenticate_user!
  after_action :verify_authorized

  def approve
    @event = Event.find(params[:id])
    @event.approve!(current_user)

    redirect_to(root_path)
  end
end

The process of approving an Event has been abstracted and defined in the Event model. Not only is our controller easier to understand, but the approval process is now re-usable and our tests for the controller are easier to write. For example, we could stub out the approve! method rather than having to check all the side effects of approving an Event. Here’s what our controller specs might look like now:

require 'rails_helper'

describe EventsController do
  describe 'PATCH approve' do
    subject(:approve_event) { patch :approve, id: event.id }

    let(:event) { FactoryGirl.create(:event, approved: false) }

    context "when authenticated && authorized to approve the Event" do
      sign_in_as(:administrator)

      it "approves the Event" do
        expect(event).to receive(:approve!).with(current_user)
        approve_event
      end

      it { should redirect_to(root_path) }
    end

    context "when not authenticated to approve the Event" do
      it_behaves_like "a controller action that has failed an authentication check"
    end

    context "when not authorized to approve the Event" do
      sign_in_as(:public_user)

      it_behaves_like "a controller action that has failed an authorization check"
    end
  end
end

However, there is a cost. The Event model has grown larger and the number of responsibilities in the Event model has increased. This makes the class harder to understand, which in turn means that:

  • The risk of defects being introduced is increased
  • Refactoring the class is more difficult
  • Tests are harder to read and write. When tests are hard to write, lazy developers sometimes “forget” to write them.
  • Most importantly: The code becomes a pain in the ass to work on

To prevent bloating our model, this workflow needs to be encapsulated in another class.

Encapsulating the workflow in a model

My preference for encapsulating such a workflow is to create another class. I just think of this class as another model, but some folk prefer to call them domain objects. Here’s a decent explanation from StackOverflow.

In the example above, I’d create a model called Event::Approver to encapsulate approving an Event.

I nest Event::Approver under Event because it is a subset of the workflows in the application that are related to the Event model.

Due to the way that Rails loads files, the file will need to be in the folder app/models/event. This is convenient since I can now look in this folder to find any workflows related to the Event model.

The Event::Approver model will look like:

class Event::Approver

  attr_reader :approver, :event

  def initialize(event, approver)
    @approver = approver
    @event = event
  end

  def approve!
    event.status = :approved
    event.approved_at = Time.now
    event.approved_by = approver
    event.save!
  end

end

The specs for this model will be equally concise, looking something like:

describe Event::Approver do
  describe "#approve!" do
    subject { Event::Approver.new(event, user).approve! }

    let(:event) { FactoryGirl.create(:event, approved: false) }
    let(:user)  { FactoryGirl.create(:user) }
    let(:current_time) { Time.now }

    before { Timecop.freeze(Time.local(1990)) }
    after  { Timecop.return }

    specify { expect { subject }.to change { event.reload.approved? }.to(true) }
    specify { expect { subject }.to change { event.reload.approved_by }.to(user) }
    specify { expect { subject }.to change { event.reload.approved_at }.to(current_time) }
  end
end

The implementation of this class is not especially important. For example, some developers will prefer not to use an initializer and will pass the event and approver directly into the approve! method.

This class is easy to understand as it has a single responsibility. The class is small enough that I can read it and understand it in only a few seconds. I don’t need to search in some 800 line of code Event model for this single method.

Similarly, the tests for the class are straight forward and easy to read and understand. The test file will be quite small, as opposed to the colossal test file that exists for the Event model.

One of the less thought about features of composing classes this way is that if I need to look at the git history for this class, 100% of the commits will be related to this single piece of functionality. I recently found out that is invaluable for when you need to work out why a process has changed. Imagine sifting through all the commits on the Event model trying to work out where function X changed (yeah, I know you can use grep – but what if the method name changed? A pain in the ass, for sure).

With our new model the controller would now look slightly different than before, but is just as skinny:

class EventsController < ApplicationController
  before_action :authenticate_user!
  after_action :verify_authorized

  def approve
    @event = Event.find(params[:id])
    Event::Approver.new(@event, current_user).approve!

    redirect_to(root_path)
  end
end

In defence of “Skinny Controller, Fat Model”

To be perfectly honest, I doubt the intention of “Skinny Controller, Fat Model” is to just blindly jam all your controller code into ActiveRecord models. I suspect it’s more likely that it means “Skinny Controllers, Fat Model Layer”.

That being said – I think it is all too easy for inexperienced developers to take the phrase literally and do just that. In fact, I have six years of experience working with developers who have zealously bloated ActiveRecord models to prevent controllers from having more responsibilities. Including myself for a time.

In summary…

When it comes to refactoring, cleaning up a controller doesn’t really benefit the health of your application if it causes a model to get dirtier.

Rather than adding more and more responsibilities to ActiveRecord models, we can create new single-purpose classes (domain objects, if you like) to encapsulate these workflows.

By doing this we make smaller classes that are easier to understand, easier to maintain, and easier to test.

Further Reading:

  1. “”Fat model, skinny controller” is a load of rubbish” by Jon Cairns
  2. “Skinny Controllers, Skinny Models” by Joe Ferris