loading...
Main Street

delegate_to in Rails

shilpi230 profile image Shilpi Agrawal ・1 min read

Ruby is known as Developer's favourite language, for a reason. Why it shouldn't when it makes our life so easier. ❤️

delegate_to is another wonderful library, as its name sounds it means delegating your work to someone else. In programmitcal word, provides a delegate class method to easily expose contained objects’ public methods as your own.

delegate_to is a very easy to go method with ActiveRecord in Rails.

The very basic example of how to use it is given below.

Alt Text

Whenever a method is dependent on the presence of another object, we always have the fear of getting NoMethodError and to solve that delegate_to has an option of allow_nil to return nil if object is not present.

class User < ActiveRecord::Base
  has_one  :profile
  delegate :first_name, to: :profile, allow_nil: true
end
User.new.first_name
>> gives nil if profile is not present.

We could pass more than one method to be delegated.

class User < ActiveRecord::Base
  has_one  :profile
  delegate :first_name, :age, :last_name, to: :profile, allow_nil: true
end

To make the delegated method more readable, it comes with an option of prefix

Alt Text

Hope you like it. And you find it useful for your next method callings. Don't forget to show some love. Thank you.

Discussion

pic
Editor guide
Collapse
bizzibody profile image
Ian bradbury

Great tip.