delegate not in the Rails API
Jun 4th, 2008 by Matt Elhotiby - Tags: ActiveRecord, Add new tag
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
You can leave a response, or trackback from your own site.
Good post, but did you mean to say “delegate NOW in the Rails API” instead of “delegate NOT in the Rails API”?
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.
One neat trick to avoid exceptions when the association isn’t compulsory is to do:
delegate :taxid, :to => ‘(organization or return nil)’
thanks Tekin, will have to use that one