假设我有一个模型 Doctor
和一个模型 Patient
。 Patient belongs_to a Doctor
。
一个 Doctor
有一个属性 office
。
我想,给定一个Patient p
,能够说p.office
并访问p的
的医生。 office
我总是可以写一个方法
class Patient
belongs_to :doctor
def office
self.doctor.office
end
但是有没有一种更自动的方法可以将 Doctor
的所有属性方法公开给 Patient
?也许使用 method_missing
来获得某种包罗万象的方法?
最佳答案
你可以使用 delegate .
class Patient
belongs_to :doctor
delegate :office, :to => :doctor
end
您可以在一个委托(delegate)方法中拥有多个属性。
class Patient
belongs_to :doctor
delegate :office, :address, :to => :doctor
end
关于ruby-on-rails - 访问父对象属性的 "rails way"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12878792/