Rails Delegate Method

Hi Folks,

I was wondering when and why you would use delegate method. So a simple example from the docs.

class User < ActiveRecord::Base
  has_one :profile
  delegate :name, :to => :profile

Ok so now we have a clean way of getting the user profiles name

<%= @user.name %>

But is this a real advantage instead of doing.

<%= @user.profile.name %>

Also by using delegation are we eliminating +1n queries?


There’s a great section in Ruby Science (which you have access to for free as a Prime subscriber) about this. I recommend checking that out.