DEV Community

Shilpi Agrawal
Shilpi Agrawal

Posted on • Updated on

delegate_to in Rails

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
Enter fullscreen mode Exit fullscreen mode
User.new.first_name
>> gives nil if profile is not present.
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (1)

Collapse
 
bizzibody profile image
Ian bradbury

Great tip.