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

你说的曾经没有我的故事 提交于 2019-12-08 16:43:54

问题


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?


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/12878792/what-is-the-rails-way-to-access-a-parent-objects-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!