什么是"轨道的方式和QUOT;访问父对象的属性? [英] What is the "rails way" to access a parent object's attributes?
本文介绍了什么是"轨道的方式和QUOT;访问父对象的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们说我有一个模型博士
,以及模型患者
。 A 病人belongs_to的博士
。
Let's say I have a model Doctor
, and a model Patient
. A Patient belongs_to a Doctor
.
A 博士
有一个属性办公
。
我会想,给定一个患者P
,可以说 p.office
并访问办公
P
的医生。
I would want to, given a Patient p
, be able to say p.office
and access the office
of p
's Doctor.
我总是可以写一个方法
class Patient
belongs_to :doctor
def office
self.doctor.office
end
但有一个更加自动化的方式来揭露所有的博士
的属性方法到患者
?也许使用的method_missing
有某种包罗万象的方法?
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?
推荐答案
您可以使用 委托
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
这篇关于什么是"轨道的方式和QUOT;访问父对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文