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
June 1st, 2007 at 9:29 am
This is really neat — but do you know why I can’t find this
delegatein the Rails or Ruby-core API docs?(I looked up this post after noticing
delegatein a friend’s rails app)June 1st, 2007 at 9:31 am
…huh. I was expecting <code> to look like <tt>. oops. :)
June 1st, 2007 at 9:35 am
A very good question Ed. I’m not sure why its not documented in the rails API. I know I’ve come across quite a few things that I found on my own that weren’t in the API and it sure would have been helpful to find them explained clearly in the API.
November 3rd, 2008 at 10:10 pm
[...] al final hablaba de un delegate que tenía un nuevo feature. Buscando un rato por google encontré este post donde hablaba de un método delegate para hacer justamente esto que yo [...]
November 27th, 2008 at 1:23 pm
Good explanation about delegate in active record. Now I got it.
June 18th, 2011 at 1:53 pm
Since this is the first result on google, i thought i might add a little update to the syntax:
delegate :year, :month, :day, :to => :published_at
and current documentation on it:
http://api.rubyonrails.org/classes/Module.html#method-i-delegate
Leave a Reply