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.
我想,如果有患者p,可以说p.office并访问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?
但有没有更自动的方式将所有Doctor的属性方法暴露给患者?也许使用method_missing来拥有某种catch-all方法?
2 个解决方案
#1
8
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
2
I believe you are talking about using Patient as a delegator for Doctor.
我相信你在谈论使用Patient作为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:
我认为这将是method_missing方式:
def method_missing(method, *args)
return doctor.send(method,*args) if doctor.respond_to?(method)
super
end
#1
8
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
2
I believe you are talking about using Patient as a delegator for Doctor.
我相信你在谈论使用Patient作为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:
我认为这将是method_missing方式:
def method_missing(method, *args)
return doctor.send(method,*args) if doctor.respond_to?(method)
super
end