Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "rails way" to access a parent object's attributes?

Let's say I have a model Doctor, and a model Patient. A Patient belongs_to a Doctor.

A Doctor has an attribute office.

I would want to, given a Patient p, be able to say p.office and access the office of p's Doctor.

I could always write a method

class Patient
    belongs_to :doctor
    def office
        self.doctor.office
    end

But is there a more automatic way to expose all of the Doctor's attribute methods to the Patient? Perhaps using method_missing to have some kind of catch-all method?

like image 550
Tim Avatar asked Oct 14 '12 02:10

Tim


2 Answers

You could use delegate.

class Patient
    belongs_to :doctor
    delegate :office, :to => :doctor
end

You could have multiple attributes in one delegate method.

class Patient
    belongs_to :doctor
    delegate :office, :address, :to => :doctor
end
like image 154
xdazz Avatar answered Nov 12 '22 10:11

xdazz


I believe you are talking about using Patient as a delegator for Doctor.

class Patient < ActiveRecord::Base
  belong_to :doctor

  delegate :office, :some_other_attribute, :to => :doctor
end

I think this would be the method_missing way of doing this:

def method_missing(method, *args)
  return doctor.send(method,*args) if doctor.respond_to?(method)
  super
end
like image 22
Zach Kemp Avatar answered Nov 12 '22 11:11

Zach Kemp