Veerasundaravel's Ruby on Rails Weblog

September 15, 2010

Rails delegate method

Filed under: Ruby On Rails — Tags: , , , , , , , , , — Veerasundaravel @ 2:36 pm

Delegation is a feature Rails introduced in it’s 2.2 version. The concept of delegation is to take some methods and send them off to another object to be processed.

Lets walk through some example:

Suppose you have a User model to save all of the registered user’s details, and also the user can have their individual profile. So the class definitions will become as follows:

class User < ActiveRecord::Base
has_one :profile
end

class Profile < ActiveRecord::Base
belongs_to :user
end

Assume you stored fullname and address details of a particular user in profile model. So you can access the fullname of a particular user using

@user.proflie.fullname

But Delegation allows you to simplify this as follows:

class User < ActiveRecord::Base
has_one :profile
delegate :fullname, :address, :to => :profile
end

class Profile < ActiveRecord::Base
belongs_to :user
end

Now you can directly access the user profile’s fullname and address as follows:

@user.fullname
@user.address

Delegates With Prefixes:

More even you can specify some prefix with your delegates like below:

class User < ActiveRecord::Base
has_one :profile
delegate :fullname, :address, :to => :profile, :prefix => true
delegate :phone, :email, :to => :profile, :prefix => “office”
end

And now you can access the user profile’s details as follows:

@user.profile_fullname
@user.profile_address
@user.office_phone
@user.office_email

Reference Links:

http://apidock.com/rails/Module/delegate
http://blog.wyeworks.com/2009/6/4/rails-delegate-method

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment