Luke
Luke

Reputation: 4925

Help with a complex ActiveRecord query that has too many joins

I have the following models

class User < ActiveRecord::Base
  has_many :occupations,     :dependent => :destroy
  has_many :submitted_jobs,  :class_name => 'Job', :foreign_key => 'customer_id'
  has_many :assigned_jobs,   :class_name => 'Job', :foreign_key => 'employee_id'
end

class Job < ActiveRecord::Base
  belongs_to :customer, :class_name => 'User', :foreign_key => 'customer_id'
  belongs_to :employee, :class_name => 'User', :foreign_key => 'employee_id'
  belongs_to :field
end

class Occupation < ActiveRecord::Base
  belongs_to :user
  belongs_to :field
  belongs_to :expertise
end

along with Field (just name and id) and Expertise (name and integer rank).

I need to create a filter that works like the following pseudocode

select * from jobs where employee_id == current_user_id
or employee_id == 0
  and current_user has occupation where occupation.field == job.field
  and if job.customer has occupation where occupation.field == job.field
    current_user.occupations must include an occupation where field == job.field
      and expertise.rank > job.customer.occupation.expertise.rank

You can see how I quickly exhaust my knowledge of SQL with a query this complex.

How would you do it? The proper SQL would be great, but if a Rails person can point me towards the correct way to do it with ActiveRecord methods, that's great too. Or maybe I'm not structuring my models very well; I'm open to all kinds of suggestions.

Thanks!

Upvotes: 0

Views: 645

Answers (1)

Fonsan
Fonsan

Reputation: 121

I might have missed something and did not look into refactoring the models but heres something that might help you to a complete solution or how to reformulate your query

The code is not tested or syntax checked

@jobs = Job.
    joins(:employee,:occupation).
    includes(:customer => {:occupations => :expertise}).
    where(:employee_id => current_user.id).
    where("occupations.field_id = jobs.field_id").all

user_occupations = current_user.occupations.include(:expertise)

user_occupations_by_field_id = user_occupations.inject({}) do |hash,oc|
    hash[oc.field_id] = oc
    hash
end

@jobs.reject! do |j|
  common_occupations = j.customer.occupations.select do |oc|
    if c = user_occupations_by_field_id[oc.field_id]
        !user_occupations.select do |eoc|
            c.field_id == eoc.field_id && c.expertise.rank > oc.expertise.rank
        end.empty?
    else
        true
    end
  end

end

Upvotes: 2

Related Questions