8

DoctorモデルとモデルがあるとしましょうPatient。A。Patient belongs_to a Doctor_

ADoctorには属性がありますoffice

私は、与えられた、の医者と言ってアクセスできるようにしたいと思いPatient pますp.officeofficep

私はいつでもメソッドを書くことができました

class Patient
    belongs_to :doctor
    def office
        self.doctor.office
    end

Doctorしかし、すべての属性メソッドを?に公開するより自動化された方法はありPatientますか?おそらくmethod_missing、ある種のキャッチオールメソッドを使用するために使用していますか?

4

2 に答える 2

8

デリゲートを使用できます。

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

1つのデリゲートメソッドに複数の属性を含めることができます。

class Patient
    belongs_to :doctor
    delegate :office, :address, :to => :doctor
end
于 2012-10-14T02:44:34.357 に答える
2

あなたはPatientをDoctorの委任者として使用することについて話していると思います。

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
于 2012-10-14T02:43:33.807 に答える