0

I've got two models: Patient and Provider joined through a table Chart.

I used the association "has_many :through" [rather than "has_and_belongs_to_many"] because i need to have another column in the Chart table [called patient_mrn]

What I'm trying to do is to show a given patient and all its associated providers [each with its name and specific patient_mrn].

I do this by grabbing all the charts that contain a given patient_ID. Then i can easily display the patient_mrn from each chart using

<%= chart.patient_mrn %>

But when i try to reach through the chart to the provider model to grab the provider name using

<%= chart.provider.provider_name %> 

I get an 'undefined method `provider_name' for nil:NilClass' error.

What am I doing wrong here? Here is more detail from the code:

The Patient model has:

has_many :charts
has_many :providers, :through => :charts

The Provider model has:

has_many :charts 
has_many :patients, :through => :charts

and the Chart model has:

belongs_to :patient
belongs_to :provider

Then in my show action in the patient controller i have:

@patient = Patient.find(params[:id])
@charts = Chart.where(:patient_id => @patient.id)

And in my show view for patient i have:

<h2>Listing Providers</h2>

 <table>
  <tr>
    <th>Patient mrn</th>
    <th>Provider</th>
  </tr>

<% @charts.each do |chart| %>
  <tr>
    <td><%= chart.patient_mrn %></td>
    <td><%= chart.provider.provider_name %></td>
  </tr>
<% end %>
</table>
4

1 回答 1

0

这是因为你得到chart.provider的是nil.

在您的charts表格中,您可能有行null provider_id

或者

在您的表中,表providers中没有记录(id)provider_idcharts

尝试:

<td><%= chart.provider.try(:provider_name) %></td>

在 nil 上调用 try 总是返回 nil。在浏览可能返回 nil 的关联时,它变得特别有用。

于 2013-04-29T06:23:23.450 回答