首页 > 解决方案 > 如何在rails中组合两个joins.where

问题描述

帮助在一个大、好或语法上加入查询,以便每个公司都有点应用程序,其中

这是 2 个单独工作的查询字符串。

DotApplication.all.joins(:current_stage_event).where(current_stage_event: {event: "prospect"}).joins('LEFT JOIN tasks on tasks.subject_id = dot_applications.id').where(tasks: {id: nil})

Company.all.joins(:users).where(users: { notification_for_active_prospects: true})

我想要的是:

Company.each do |company|
  # For each company(with joins,where above), find all dot_applications as in the examples above
end

CompanyDotApplication之间的关联如下所示:

# app/models/company.rb
class Comany < ApplicationRecord
  has_many :dot_aplications
end

# app/models/dot_application.rb
class DotApplication < ApplicationRecord
  belongs_to :company
end

标签: ruby-on-railsruby

解决方案


Company.joins(:dot_applications)
       .where(dot_appplications: DotApplication.joins(:current_stage_event)
                                               .where(current_stage_event: {event: "prospect"})
                                               .joins('LEFT JOIN tasks on tasks.subject_id = dot_applications.id')
                                               .where(tasks: {id: nil}))
       .joins(:users)
       .where(users: { notification_for_active_prospects: true})

这应该找到所有满足您要求的公司DotApplication,然后查询这些公司的User要求


推荐阅读