尝试链接到患者资料时出错

时间:2019-01-18 19:35:27

标签: ruby-on-rails ruby

当提供者查看他的患者列表时,尝试链接到患者档案时出现错误。在显示属于提供者的所有患者姓名时,我没有问题,但是当尝试链接到患者资料时,我得到了一个未定义的方法“ id”。

因此,它的工作方式是,患者可以搜索提供者并将其添加到List模型中。在提供者方面,我只列出添加了该特定提供者的所有患者。这是下面的我的erb代码,

<div class="body">
            <div class="body">
            <% if @active_patients.count > 0 %>
                <table>
                  <thead>
                    <tr>
                      <th>Patient Name</th>
                      <th>Actions</th>
                    </tr>
                  </thead>
                  <tbody>
                    <% @active_patients.each do |list| %>
                      <tr>
                        <td>
                            <%= list.patient.role.user.first_name %> <%= list.patient.role.user.last_name %>
                        </td>
                        <td>
                            <%= link_to patient_path(id: @patient.id), class: "btn" do %>View<% end %> . #### THIS IS THE LINE
                        </td>
                      </tr>
                    <% end %>
                  </tbody>
                </table>
            <% else %>
                <div class="no-records">
                    <%= image_tag "icon-no-records", class: "image" %>
                    <div class="text">You have no patients.</div>
                </div><!--no-records-->
            <% end %>
        </div><!--body-->
    </div>

这是我的List模型,

class List < ApplicationRecord
    belongs_to :membershipable, :polymorphic => true
    belongs_to :provider  

    def patient
      membershipable_type=='Patient' ? membershipable : nil
    end

    def provider_user
        patient.try(:user)
    end
end

这也是错误消息->

enter image description here

2 个答案:

答案 0 :(得分:0)

让Rails完成构建路径的工作。每个ActiveRecord模型都有一个to_param方法,该方法决定如何在URL中编码实例。默认情况下,它返回模型ID,但也可以是基于模型标题或其他属性的子段。

patient_path(patient)这样的助手应该可以解决问题。

此外,在当前代码中,您所引用的是以前未使用的@patient变量,尽管看起来您想引用list.patient

答案 1 :(得分:0)

这里:

<% @active_patients.each do |list| %>
  <tr>
    <td>
      <%= list.patient.role.user.first_name %> <%= list.patient.role.user.last_name %>
    </td>
    <td>
      <%= link_to patient_path(id: @patient.id), class: "btn" do %>View<% end %> . #### THIS IS THE LINE
    </td>
  </tr>
<% end %>

您可以使用变量list。看来您是通过执行patient来获得list.patient的,就像您在这里所做的一样:

<%= list.patient.role.user.first_name %> <%= list.patient.role.user.last_name %>

但是,您尝试在这里使用一个名为@patient的变量:

<%= link_to patient_path(id: @patient.id), class: "btn" do %>View<% end %> .

当您没有变量@patient时。因此,您得到nil错误。

相反,您似乎应该这样做:

<%= link_to patient_path(id: list.patient.id), class: "btn" do %>View<% end %> .

或者,正如米尔格纳指出的那样,您可以简单地做到:

<%= link_to patient_path(list.patient), class: "btn" do %>View<% end %> .

此外,您可能希望查看在执行此操作时违反(IMO)的Law of Demeter

list.patient.role.user.first_name