Note that there are some explanatory texts on larger screens.

plurals
  1. POHelp with a complex ActiveRecord query that has too many joins
    primarykey
    data
    text
    <p>I have the following models</p> <pre><code>class User &lt; ActiveRecord::Base has_many :occupations, :dependent =&gt; :destroy has_many :submitted_jobs, :class_name =&gt; 'Job', :foreign_key =&gt; 'customer_id' has_many :assigned_jobs, :class_name =&gt; 'Job', :foreign_key =&gt; 'employee_id' end class Job &lt; ActiveRecord::Base belongs_to :customer, :class_name =&gt; 'User', :foreign_key =&gt; 'customer_id' belongs_to :employee, :class_name =&gt; 'User', :foreign_key =&gt; 'employee_id' belongs_to :field end class Occupation &lt; ActiveRecord::Base belongs_to :user belongs_to :field belongs_to :expertise end </code></pre> <p>along with <code>Field</code> (just name and id) and <code>Expertise</code> (name and integer rank).</p> <p>I need to create a filter that works like the following pseudocode</p> <pre><code>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 &gt; job.customer.occupation.expertise.rank </code></pre> <p>You can see how I quickly exhaust my knowledge of SQL with a query this complex.</p> <p>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.</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload