什么是“rails方式”来访问父对象的属性?

问题描述:

比方说,我有一个型号Doctor,和一个型号Patient。 A Patient belongs_to a Doctor什么是“rails方式”来访问父对象的属性?

A 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 

您可以在一个委托方法中拥有多个属性。

class Patient 
    belongs_to :doctor 
    delegate :office, :address, :to => :doctor 
end 
+0

那么,如果除了'办公室',我还有10个其他属性,我想要“委托”到“医生”呢?我需要写10个委托书吗? – Tim

+0

@Tim你只能写一个。 – xdazz

+0

我明白了,我没有仔细阅读并意识到您可以将多个字段传递给委托。谢谢! – Tim

我相信你在谈论如何使用Patient作为医生的代理人。

class Patient < ActiveRecord::Base 
    belong_to :doctor 

    delegate :office, :some_other_attribute, :to => :doctor 
end 

我认为这将是这样做的method_missing的方式:

def method_missing(method, *args) 
    return doctor.send(method,*args) if doctor.respond_to?(method) 
    super 
end