A true leader (in Rails) knows how to delegateWhen 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:
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'
delegatemodule comes in very handy. Here's what the above example would look like using
class Course < ActiveRecord::Base
delegate :name, to: :course_name
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
courseobject 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.