0

In the console this code:

Patient.joins(:notes,:recordings).find(1)

Returns

ActiveRecord::RecordNotFound: Couldn't find Patient with id=1

Which is bizarre because in the same console Patient.find(1) works without any issue and retrieves the record of the patient with id 1.

My understanding is that I should be able to do:

a = Patient.joins(:notes,:recordings).find(1)
a.notes
a.recordings

And a.notes should return all the notes associated with the patient with id 1 and same for a.recordings. It's clear I'm missing something here...any ideas?

Morgan
  • 1,438
  • 3
  • 17
  • 32

2 Answers2

2

That's because rails does INNER JOIN by default. your patient 1 doesn't have either notes or recordings

If can do a left join instead.

Patient.joins("LEFT JOIN notes on notes.patient_id = patients.id")
       .joins("LEFT JOIN recordings on recordings.patient_id = patients.id")
       .find(1)

or load the patient and then load the associations

 a = Patient.find(1)
 a.notes
 a.recordings
usha
  • 28,973
  • 5
  • 72
  • 93
1

You may be interested in include type functionality (for eager loading). See: Rails :include vs. :joins

Community
  • 1
  • 1
Coenwulf
  • 1,937
  • 2
  • 15
  • 23