Subqueries and using an 'or' - aavedula/how-to-notes GitHub Wiki

Back

File: app/queries/pac_episodes_query.rb

def patient_has_attributions_or_was_referred_from_sponsor(relation)
  if params.patient_has_attributions_or_was_referred_from_sponsor
    relation.where(referring_hospital_has_sponsors(relation).arel.exists).or(
      relation.where(patient_has_attributions(relation).arel.exists)
    )
  else
    relation
  end
end

def referring_hospital_has_sponsors(relation)
  SponsorPopulation.where("population_id = #{relation.table_name}.hospital_id")
end

def patient_has_attributions(relation)
  PatientAttribution.where("patient_id = #{relation.table_name}.patient_id")
end