Ruby on Rails 中的自引用关联

问题描述

我有一个应用程序,其中包含“患者”资源。我想在与病毒感染有关的患者之间建立自我关联。因此,患者可以是感染者、感染者或两者兼而有之。当我创建一个病人时,我想选择哪个(另一个)病人感染了他。所以我在“Patient”中添加了一个“patient_id”字段。我的代码如下:

患者模型:

  class Patient < ApplicationRecord
      has_many :infected,class_name: 'Patient',foreign_key: :patient_id
      belongs_to :infectant,optional: true,class_name: 'Patient'
  end

患者表格:

<div class="field">
      <%= form.label :patient_id %>
      <%= form.collection_select(:patient_id,Patient.all,:id,:document_number) %>
    </div>

  <div class="field">
    <%= form.label :first_name %>
    <%= form.text_field :first_name %>
  </div>

  <div class="field">
    <%= form.label :last_name %>
    <%= form.text_field :last_name %>
  </div>

  <div class="field">
    <%= form.label :document_number %>
    <%= form.number_field :document_number %>
  </div>

  <div class="field">
    <%= form.label :birth_date %>
    <%= form.datetime_select :birth_date %>
  </div>

  <div class="field">
    <%= form.label :province %>
    <%= form.number_field :province %>
  </div>

  <div class="field">
    <%= form.label :city %>
    <%= form.text_field :city %>
  </div>

  <div class="field">
    <%= form.label :status %>
    <%= form.number_field :status %>
  </div>

患者索引:

<table>
  <thead>
    <tr>
      <th>First name</th>
      <th>Last name</th>
      <th>Document number</th>
      <th>Birth date</th>
      <th>Province</th>
      <th>City</th>
      <th>Status</th>
      <th>Infectant</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @patients.each do |patient| %>
      <tr>
        <td><%= patient.first_name %></td>
        <td><%= patient.last_name %></td>
        <td><%= patient.document_number %></td>
        <td><%= patient.birth_date %></td>
        <td><%= patient.province %></td>
        <td><%= patient.city %></td>
        <td><%= patient.status %></td>
        <td><%= patient.patient_id %></td>
        <td><%= link_to 'Show',patient %></td>
        <td><%= link_to 'Edit',edit_patient_path(patient) %></td>
        <td><%= link_to 'Destroy',patient,method: :delete,data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

使用此索引,我可以显示感染者的 ID。 我想要的是在索引中显示感染者的“document_number”。但是如果不是“patient.patient_id”,我写的是“patient.infectant.document_number”,但因为“Patient”没有“infected”字段,它会返回错误。

解决方法

解决此问题的一种方法是使用 delegate

class Patient < ApplicationRecord
  # ...
  delegate :document_number,to: :infectant,prefix: true,allow_nil: true
end

这会让你打电话:

<td><%= patient.infectant_document_number || "default value" %></td>

没有零错误的风险。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...