ActiveRecord:搜索与 AND 条件关联的多个 id

ActiveRecord: Search for multiple ids in association with AND condition

我有以下型号

class Employee < ApplicationRecord
   has_many :employee_skills
   has_many :skills, throught: :employee_skills
end

class Skill < ApplicationRecord
   has_many :employee_skills
   has_many :employees, through: :employee_skills
end

class EmployeeSkill < ApplicationRecord
   belongs_to :employee
   belongs_to :skill
end

我如何查询具有技能 1 AND 2 AND 3(或更多技能)的员工。 Array conditions (see Rails Guide) 选择 OR 而不是 AND。

如果你想申请所有员工,你可以简单地使用includes,如果你想申请单个员工,你可以这样做

@employee.skills.where(id: array_of_ids)

包括所有或超过 1 名员工

Employee.includes(:skills).where('skills.id' => array_of_ids)

根据@sebastian 的评论,您可以使用连接

Employee.joins(:skills).where(skills: { id: [1,2,3,4] })

一种可能的方法是在 joins:

中使用您自己的自定义 "raw" 连接条件
Employee
  .joins('INNER JOIN skills s1 ON s1.id = 1 AND s1.employee_id = employees.id')
  .joins('INNER JOIN skills s2 ON s2.id = 2 AND s2.employee_id = employees.id')

这里s1.id和s2.id都是你拥有的技能id

受此处解决方案的启发:SELECTING with multiple WHERE conditions on same column,这是仅使用活动记录的解决方案

Employee.joins(:employee_skills).where(employee_skills: {skill_id: @skills.ids})
        .group('employees.id, employee_skills.employee_id')
        .having('COUNT(*) = ?', @skills.count)