← Back to Upcase

Rails Delegate Method


(Lee Smith) #1

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
end

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?

Lee


(Ben Orenstein) #2

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.