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>