双has_many关联仅返回第二个关联之一

时间:2019-02-11 07:41:31

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

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

3 个答案:

答案 0 :(得分:1)

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

您可以尝试如下操作:

class Patient
  belongs_to :doctor
  has_many :historics

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

答案 1 :(得分:0)

您需要其他设置。

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

Player2 200
Player1 100
Player3 50

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

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

在控制台内部:

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

答案 2 :(得分: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

也许这不是很“合理”,但对我有用。

相关问题