Tuesday, May 22nd, 2007...9:25 am

ActiveRecord Delegate Attributes

Jump to Comments

I finally started using a pretty handy feature of ActiveRecord: delegate attributes. I first came across the delegate syntax while looking through the Mephisto codebase a while back. Mephisto has the following line in one of their models:

class Content < ActiveRecord::Base
  [:year, :month, :day].each { |m| delegate m, :to => :published_at }
end

I saw that delegate line and never really thought much about it. It may be easier to read the previous line as individual statements instead of the block format.

class Content < ActiveRecord::Base
  delegate :year, :to => :published_at
  delegate :month, :to => :published_at
  delegate :day, :to => :published_at
end

What the delegate method does is allow you to access those methods in “shortform”.

# the :to option specifies which object you want
# to access the delegated method from

# This allows you to write
@content.year

# as a shortcut for
@content.published_at.year

Pretty handy for certain uses. Try it out.

** UPDATE **

Updated to include link to Rails API Documentation per mooman’s comment below:

http://api.rubyonrails.org/classes/Module.html#method-i-delegate

6 Comments

© 2020 Craig P Jolicoeur.