双的has_many协会第二协会只返回一个

问题描述 投票:0回答:3
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

ruby-on-rails ruby-on-rails-5 model-associations
3个回答
1
投票

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

您可以尝试这样的事:

class Patient
  belongs_to :doctor
  has_many :historics

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

0
投票

你需要一个不同的设置。

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

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

现在你已经建立了这个连接,你需要与historics添加额外的关联关系:

Class Patient
  belongs_to :doctor
  has_many :historics
end

Class Historic
  belongs_to :doctor
  belongs_to :patient
end

最后,调整医生:

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

控制台里面:

d = Doctor.last

d.patients.last.historics.last

0
投票

谢谢大家的答案。我落得这样做是因为我用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

也许这是不是很“轨道的方式”,但这项工作对我来说。

© www.soinside.com 2019 - 2024. All rights reserved.