Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double Join Query Rails

I have three models, JobPosting, Job, and Organization. The relations are below:

  1. An Organization has many Jobs.
  2. A Job belongs to an Organization and has many JobPostings.
  3. A JobPosting belongs to a Job.

A Job has an attribute called job_type, and I am able to find all of the JobPostings that are related to a Job with a specific job_type using the query:

JobPosting.joins(:job).where(jobs: { :job_type => 'volunteer' })

But what I am struggling with is doing the same kind of thing but with an Organization attribute. A Organization has a attribute called department, how can I query for the JobPosting's that relate to an organization through a Job that has a specific department. The reason I am having trouble is because Organizations are essentially two levels up, whereas Job's are only one.

Any help would be greatly appreciated.

like image 343
Robert Saunders Avatar asked Mar 28 '17 22:03

Robert Saunders


1 Answers

You can join the two relations as follows:

JobPosting.
  joins(job: :organization).
  where(jobs: { job_type: 'volunteer' }, organizations: { organizations_attr1: 'value_to_test' })

joins(job: :organization) ensures you have inner joins between job_postings, jobs and organizations tables correctly. Try executing this in the rails console with .to_sql to check the generated query if you want to explore how Rails performs joins.

like image 94
vee Avatar answered Nov 15 '22 11:11

vee