【问题标题】:What is the "rails way" to access a parent object's attributes?访问父对象属性的“rails 方式”是什么?
【发布时间】:2012-10-14 02:23:44
【问题描述】:

假设我有一个模型 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 有某种包罗万象的方法?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord model


    【解决方案1】:

    您可以使用 delegate

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

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

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

    【讨论】:

    • 那么,如果除了office,我还有10 个其他属性我想“委托”给doctor 怎么办?我需要写 10 个delegate 声明吗?
    • @Tim 你只能写一个。
    • 我明白了,我没有仔细阅读并意识到您可以传递多个字段来委托。谢谢!
    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      • 2015-06-08
      • 1970-01-01
      相关资源
      最近更新 更多