Double Join Query Rails

I have three models: JobPosting, Job and Organization. Below are the ratios:

  • There are many Jobs in the Organization.
  • The job is owned by an organization and has many JobPostings.
  • JobPosting belongs to the job.

The job has an attribute job_type

and I can find all JobPostings associated with a job with a specific one job_type

using a query:

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

      

But what I am struggling with does the same thing but with the Organization attribute. The organization has an attribute department

, how can I request JobPosting, which are related to the organization via a Job that has a specific department. The reason I am having trouble is because organizations are essentially on two levels, while Job is only one.

Any help would be greatly appreciated.

+3


source to share


1 answer


You can connect two relationships like this:

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

      



joins(job: :organization)

ensures correct inner join between tables job_postings

, jobs

and organizations

. Try this in rails console

with .to_sql

to check the generated request if you want to learn how Rails performs joins.

+4


source







All Articles