繁体   English   中英

帮助处理具有太多连接的复杂 ActiveRecord 查询

[英]Help with a complex ActiveRecord query that has too many joins

我有以下型号

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

以及Field (仅名称和 ID)和Expertise (名称和 integer 等级)。

我需要创建一个类似于以下伪代码的过滤器

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

你可以看到我是如何通过这个复杂的查询快速耗尽我对 SQL 的了解的。

你会怎么做? 正确的 SQL 会很棒,但是如果 Rails 人可以指出我使用 ActiveRecord 方法的正确方法,那也很棒。 或者也许我没有很好地构建我的模型; 我愿意接受各种建议。

谢谢!

我可能遗漏了一些东西并且没有考虑重构模型,但是这里有一些东西可能会帮助您获得完整的解决方案或如何重新制定您的查询

代码未经测试或语法检查

@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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM