2017-08-09 117 views
0

我在我的应用程序中有两个表和四个模型。第一个模型是公司,它有公司的表格。其他模型是员工,司机和主管。我在我的应用程序中使用了单表继承。Ruby On Rails自联接关联

公司型号:

class Company < ApplicationRecord 

    has_many :employees 

end 

而且表结构

ID NAME 
1 XXX company 

和员工,司机和监事型号:

class Employee < ApplicationRecord 

    belongs_to :company 

end 

class Chef < Employee 


end 

class Driver < Employee 


end 

class Supervisor < Employee 


end 

和员工表结构:

ID NAME COMPANY_ID TYPE 
1 Jo  1   Supervisor 
2 Jack 1   Driver 
3 William 1   Driver 
4 Avarell 1   Driver 
5 Sam  1   Chef 

我需要做的是我希望主管通过has_many关联访问属于同一公司的所有驱动程序。

我曾尝试下面这段代码在主管类:

has_many :drivers, ->(supervisor) {where(company: supervisor.company)} 

然而,轨道创建下面的SQL,这是不是我期待

SELECT `employees`.* FROM `employees` WHERE `employees`.`type` IN ('Driver') AND `employees`.`supervisor_id` = 4 AND `employees`.`type` IN ('Driver', 'Supervisor') AND `employees`.`company_id` = 1 

我想轨在构建关联时创建这样的查询。

SELECT `employees`.* FROM `employees` WHERE `employees`.`type` IN ('Driver') AND `employees`.`company_id` = 1  

任何suggesstions,

感谢。

+0

做一个'驱动程序''has_one:supervisor'?或者这种关联不重要? –

回答

2

您可以通过belongs_to关联执行has_many :through

例如,您可以访问同一家公司的Supervisordriverschefs。您将无法倒退并找到Driversupervisor

class Company < ApplicationRecord 
    has_many :employees 
end 

class Employee < ApplicationRecord 
    belongs_to :company 
end 

class Chef < Employee 
end 

class Driver < Employee 
end 

class Supervisor < Employee 
    has_many :drivers, through: :company, source: :employees, class_name: 'Driver' 
    has_many :chefs, through: :company, source: :employees, class_name: 'Chef' 
end 

它触发的SQL查询

SELECT "employees".* FROM "employees" INNER JOIN "companies" ON "employees"."company_id" = "companies"."id" WHERE "employees"."type" IN ('Driver') AND "companies"."id" = 1 

正是你预想的查询,但它的工作原理。

+0

谢谢你的作品。我找到了另一个解决方案。 has_many:drivers,primary_key ::'company_id',foreign_key ::'company_id'这就创建了我期望的查询 –

+0

这是个好主意! –