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
endclass 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
endclass 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