Search code examples
ruby-on-railsactiverecord

Two level ActiveRecord query


Factory has_many Worker through JobRole, for example.

factory model:

has_many :workers, through: :job_roles

worker model:

has_many :job_roles
has_many :factories, through: :job_roles

job_role model:

belongs_to :worker
belongs_to :factory

query:

factory.job_roles.where(heavy_lifting:true, sensitive_area: false).workers.where.not(confirmed_at:nil).pluck(:work_capacity)

The first .where query is an ActiveRelation, calling .workers on it fails.

I need pull the work_capacity of the workers who have specific job_roles within a factory.

Any way to do this other than looping through the first query to put the worker's work capacity in an array?

i.e.:

applicable_job roles = factory.job_roles.where(heavy_lifting:true, sensitive_area: false)

work_capacities = []

applicable_job_roles.each do |job_role|
 if job_role.confirmed_at != nil
 work_capacities << job_role.work_capacity
end

Solution

  • factory.workers.where.not(confirmed_at:nil).where(job_roles: {heavy_lifting:true, sensitive_area: false}).pluck(:work_capacity)