There are these models:
Patient
Patient has_many MedicalOrders
MedicalOrder
MedicalOrder belongs_to Patient
MedicalOrder has_many Tasks
Task
Task belongs_to MedicalOrder
Task has_many ControlMedicines
ControlMedicine
ControlMedicine belongs_to Task
And there's this block of code to get the actual @patient's control_medicines:
def index
@control_medicines = []
@patient.medical_orders.each do |mo|
mo.tasks.order(created_at: :desc).each do |t|
t.control_medicines.each do |cm|
@control_medicines << cm
end
end
end
end
I know it's not the best way to query associated models but haven't figured out how to do it using .includes()
method. Mostly because .includes()
only works being called to a Class (eg, Patient.includes()
) and they're not suitable for nested models, like in this situation.
I've read about preloading, eager_loading and includes but all the examples are limited to get data from two associated models.