Hi all,
I have a question regarding associations. I’m trying to preload some associations (a patient belongs_to cdoctor, gp and pharmacy) and then access fields from those associations.
The page is being used to show a summary of all patients in the system, listed as a table with, where each row has a patient, their cdoctor, their gp and their pharmacy.
Each patient holds a value for gp_id, pharm_id, cdoctor_id.
Currently the page shows the following (as expected):
I however want to show the GP name, Pharmacy name etc. instead of their ID, which I believe is possible by preloading the associations.
The question I have is how do you do this? I’ve had a read online, but I can’t understand some of the explanations, and none seem to demonstrate how to access those variables (my idea of how it works is dot-walking, perhaps like patient.gp_id.name).
Here’s my current code for preloading, which I’m almost certain is incorrect, but compiles successfully:
patients = Repo.all(Patient) |> Repo.preload([:gps, :pharms, :cdoctors])
And here’s the page displaying the data:
<h2>Patients</h2>
<div class="panel panel-primary">
<table class="sortable table">
<thead>
<tr>
<th scope="col"><button type="button" class="btn btn-primary">Patient Name</button></th>
<th scope="col"><button type="button" class="btn btn-primary">GP</button></th>
<th scope="col"><button type="button" class="btn btn-primary">Clinic Doctor</button></th>
<th scope="col"><button type="button" class="btn btn-primary">Pharmacy</button></th>
</tr>
</thead>
<tbody>
<%= for p <- @patients do %>
<tr>
<th scope="row"><%= link p.fname<>" "<>p.lname, to: patient_path(@conn, :show, p), class: "" %><br></th>
<td><%= link p.gp_id, to: gp_path(@conn, :show, p.gp_id), class: "" %></td>
<td><%= link p.cdoctor_id, to: c_doctor_path(@conn, :show, p.cdoctor_id), class: "" %></td>
<td><%= link p.pharm_id, to: pharmacy_path(@conn, :show, p.pharm_id), class: "" %></td>
</tr>
<%= end %>
</tbody>
</table>
</div>
<script src="https://www.kryogenix.org/code/browser/sorttable/sorttable.js"></script>
Any helpful advice would be greatly appreciated. I can attach the code from the models if necessary, however this post is already long enough imo!
Thanks in advance