Last Updated: July 12, 2017
· tomkr

Using delegate in Rails

Using delegate makes it really simple to call a method on one class from another. This can be useful to hide the implementation of a method in a related class. Especially in models with intricate relationships you may make a lot of calls from one class to another. Rails provides a delegate macro that allows you to do this easily.

For instance we have a Book model that belongs to an Author. The Author has a name, and we can call this from the book with:


This exposes the author object even if we don't really need it, so we could do the following:

class Book < ActiveRecord::Base
  delegate :name, to: author, prefix: true

Now we can call:


and have everything work fine behind the scenes.

I think this is a nice way to clean up your code somewhat, keeping everything that belongs together in one place by following the Law of Demeter (principle of least knowledge).

3 Responses
Add your response


You can also allow_nil: true which is really helpful so it doesn't raise exceptions if the delegated object returns nil

over 1 year ago ·

For some reason, this didn't work for me unless I specified the to: argument as a symbol. Great tip, though!

over 1 year ago ·

We can also use delegate in has_one relationships. just figured out !!

over 1 year ago ·