dennismonsewicz
dennismonsewicz

Reputation: 25552

Rails 3 scope with multiple models

Here are my models:

Patient:

has_many :patient_records

PatientRecord:

belongs_to :patient
has_many :progress_reports

ProgressReport:

has_one :patient_record

The query I am trying to produce is to get all patients where progress_reports are older than or equal to 7 days from now (using a date_of_report column in progress_reports) while including or joining the patient record table... I have been working on this for so long that I have ran into a brick wall.

Upvotes: 0

Views: 388

Answers (2)

Michael Durrant
Michael Durrant

Reputation: 96614

I would try:

scope :recent_patients, lambda 
{ |since_when| join(:progress_reports)
  .where("progress_reports.created_at >= ?", since_when)}

in your Patient model

Upvotes: 2

Kosmonaut
Kosmonaut

Reputation: 2290

reports = ProgressReport.where(:created_at > 7.days.ago).all

if you want to get each patient that belongs to each record, do:

reports.each do |r|
   puts r.patient.name
end

Upvotes: 0

Related Questions