假设我有一个模型Doctor
,和一个模型Patient
. A Patient belongs_to a Doctor
.
A Doctor
有一个属性office
.
我想,给定一个Patient p
, 能够说p.office
并访问office
of p
的医生。
我总是可以写一个方法
class Patient
belongs_to :doctor
def office
self.doctor.office
end
但是有没有一种更自动的方法来公开所有的Doctor
的属性方法Patient
?也许使用method_missing
有某种包罗万象的方法吗?
你可以使用delegate http://apidock.com/rails/Module/delegate.
class Patient
belongs_to :doctor
delegate :office, :to => :doctor
end
您可以在一个委托方法中拥有多个属性。
class Patient
belongs_to :doctor
delegate :office, :address, :to => :doctor
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)