From The Blog

delegate not in the Rails API

The delegate method allows you to add contained objects methods to your current objects methods. For example suppose you have two models User and...

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

Other Posts That Might Interest You

  1. Documentation in your Rails app
  2. Custom Form Validations Without ActiveRecord
  3. Factories for test objects. Use them.

Tags: 

  • thanks Tekin, will have to use that one
  • One neat trick to avoid exceptions when the association isn't compulsory is to do:

    delegate :taxid, :to => '(organization or return nil)'
  • 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.
  • Good post, but did you mean to say "delegate NOW in the Rails API" instead of "delegate NOT in the Rails API"?
blog comments powered by Disqus