The Spaghetti Refactory Established 2015

A true leader (in Rails) knows how to delegate

When building a larger Rails app with lots of associations, I've run into an issue a few times where one object belongs to another, and I want to get the value of the parent object from the child object. This is going to get very esoteric very quickly, so let's get an example going.

Say I have a Course model with an associated CourseName (belongs_to :course_name), because I want to be able to create multiple Courses with the same name but different times and dates. Since Course does not have a name, any time I find a Course object and want to show the name, I have to call course.course_name.name. Previously, I've written a shortcut method on Course:

def name
course_name.name
end

That isn't a huge issue, but if there are a lot of CourseName methods or attributes that I want to access directly from Course, it starts to be a pain having to define a new shortcut method for each.

This is where Rails' delegate module comes in very handy. Here's what the above example would look like using delegate:

class Course < ActiveRecord::Base
belongs_to :course_name
delegate :name, to: :course_name
end

I've delegated the name method that I would have had to define in Course to the CourseName model instead, so when I am working with a course object and I call course.name, it will look for the delegated method in the model that it was delegated to, based on the association.

This delegation stuff is pretty powerful and extendable according to the docs, so I'm looking forward to playing around a bit with all the other stuff that can be done.