'ActiveRecord `join` on query result

I have something like:

class Person < ApplicationRecord
  has_many :jobs
end

class Job < ApplicationRecord
  has_and_belong_to_many :team
end

class Team < ApplicationRecord
  belongs_to :company
end

class Company < ApplicationRecord
  scope :bankrupt, -> { where(*is_bankrupt_query()) }
end

And what I want to do is get all the people who have jobs at bankrupt companies.

I can do this via the relations and Rails magic:

  scope :recruitable, -> () { joins(:companies).where(Company.is_bankrupt_query) }

but this has code smell (if not in my toy example, in the actual situation at work), although it does produce the SQL that I want (a series of nested joins).

What I think I want is something like:

Persons.join(job: Companies.bankrupt.jobs )

but, of course the jobs relation exists on instances of the model, not the ActiveRecord::Relation.

I can somewhat get around it:

Persons.where(job: Companies.bankrupt.first.jobs )

but this only works for one Company at a time, and is a where in rather than join (AFAIK that's gonna run into issues as the data sets grow).

Ideas? Am I just (as usual!) missing some neat feature that I just don't know the name of?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source