Tim*_*Tim 8 ruby activerecord model ruby-on-rails
假设我有一个模型Doctor和一个模型Patient.一Patient belongs_to a Doctor.
A Doctor有一个属性office.
我会想,给定一个Patient p,可以说p.office并访问office的p"好医生.
我总是可以写一个方法
class Patient
belongs_to :doctor
def office
self.doctor.office
end
Run Code Online (Sandbox Code Playgroud)
但有没有更自动的方式将所有Doctor的属性方法暴露给Patient?也许使用method_missing某种全能方法?
你可以使用委托.
class Patient
belongs_to :doctor
delegate :office, :to => :doctor
end
Run Code Online (Sandbox Code Playgroud)
您可以在一个委托方法中拥有多个属性.
class Patient
belongs_to :doctor
delegate :office, :address, :to => :doctor
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2455 次 |
| 最近记录: |