【问题标题】:Double has_many association return only one of the second association双has_many关联只返回第二个关联之一
【发布时间】:2019-02-11 07:41:30
【问题描述】:
Class Doctor
  has_many :patients
end

Class Patient
  belongs_to :doctor
  has_many :historics
end

Class Historic
  belongs_to :patient
end

我有这样的结构。当我是一名医生时,我想获取所有患者的列表,但只显示每个患者的最后一个历史记录。

到目前为止,我无法找到如何做到这一点。我应该创建这样的东西吗?

Class Doctor
  has_many :patients_with_one_historic, class_name: 'Historic', :through => :patient, :limit => 1
end

但在这种情况下,这将返回患者的历史模型而不是具有一个历史的患者模型?!

我使用的是 Rails 5.1.5

【问题讨论】:

  • 定义 2 关联,正如我在对patient- historic 关系的回答中提供的那样

标签: ruby-on-rails ruby-on-rails-5 model-associations


【解决方案1】:

我相信在这种情况下,编写自己的 getter 不会是世界末日。

你可以试试这样的:

class Patient
  belongs_to :doctor
  has_many :historics

  # Get the latest historic
  def latest_historic
    self.historics.last
  end
end

【讨论】:

  • 谢谢!您如何称呼医生的这种方法? @doctor.patients.latest_historic?
  • @Stéphane,您可以从任何个别患者那里调用它,例如 Patient.latest_historic。您可以调用 doctor.patients 并将其映射为 doctor.patients.map{|p| p.latest_historic} 以获取您的最新历史记录。
【解决方案2】:

谢谢大家的回答。 我最终做的是,因为我使用fast_jsonapi,来创建一个新的“轻”患者Serializer

而不是:

class PatientSerializer
  include FastJsonapi::ObjectSerializer
  set_type :patient
  attributes  :id,
              ......
              :historics
end

我现在有:

class PatientSerializerLight
  include FastJsonapi::ObjectSerializer
  set_type :patient
  attributes  :id,
              ......
              :last_historic
end

在我的患者模型中,我创建了@F.E.A 建议的方法:

def last_historic
  self.historics.last
end

现在我可以做:

@patients = @doctor.patients
PatientSerializerLight.new(@patients).serializable_hash

也许这不是很“轨道方式”,但这对我有用。

【讨论】:

    【解决方案3】:

    您需要不同的设置。

    首先,直接关系是:一个医生有很多病人。

    Class Doctor
      has_many :patients
    end
    Class Patient
      belongs_to :doctor
    end
    

    现在您已建立此连接,您需要添加与历史记录的附加关联:

    Class Patient
      belongs_to :doctor
      has_many :historics
    end
    
    Class Historic
      belongs_to :doctor
      belongs_to :patient
    end
    

    最后,调整Doctor:

    Class Doctor
      has_many :patients
      has_many :historics, through: :patients
    end
    

    在您的控制台内:

    d = Doctor.last
    
    d.patients.last.historics.last
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多