- Jun
- 04
- 2008
delegate not in the Rails API
By: Matt Elhotiby | Tags:The delegate method allows you to add contained objects methods to your current objects methods. For example suppose you have two models User and Organization….
class User < ActiveRecord::Base belongs_to :organization
class Organization < ActiveRecord::Base
has_many :users
Ok now lets say that you want to access the taxid for the employee but the taxid is in the organizations table, you would normally have to access it like this….
@a_user.organization.taxid
but with the delegate method you can insert
class User < ActiveRecord::Base belongs_to :organization
delegate :taxid, :to => :organization
and now to can skip the middle man and do…
@a_user.taxid
which returns the same result
Share this post
Other posts you may enjoy
You can leave a response, or trackback from your own site.


4 Responses to “delegate not in the Rails API”
On June 4th, 2008 at 3:04 pm Alex S. said:
Good post, but did you mean to say “delegate NOW in the Rails API” instead of “delegate NOT in the Rails API”?
On June 4th, 2008 at 3:36 pm Matt Elhotiby said:
Thanks Alex, and yes I could have named it “delegate NOW in the Rails API” but I did that on purpose because I couldn’t find the method in the rails API so I named it that.
On June 5th, 2008 at 1:52 pm Tekin said:
One neat trick to avoid exceptions when the association isn’t compulsory is to do:
delegate :taxid, :to => ‘(organization or return nil)’
On June 5th, 2008 at 1:55 pm Matt Elhotiby said:
thanks Tekin, will have to use that one