Rails 5 中的或方法的动态范围

Dynamic scope with or method in Rails 5

我的单元模型的一些范围:

class Unit < ApplicationRecord
  scope :committees,   -> { where(unit_type: UnitType.committee) }
  scope :departments,  -> { where(unit_type: UnitType.department) }
  scope :faculties,    -> { where(unit_type: UnitType.faculty) }
  scope :programs,     -> { where(unit_type: UnitType.program) }
  scope :universities, -> { where(unit_type: UnitType.university) }
end

class UnitType < ApplicationRecord
  enum group: {
    other: 0,
    university: 1,
    faculty: 2,
    department: 3,
    program: 4,
    committee: 5
  }
end

我想使用其他范围创建新范围,如下所示:

class Unit < ApplicationRecord
  ...
  scope :for_curriculums, -> { universities.or(faculties).or(departments) }
  scope :for_group_courses, -> { faculties.or(departments) }
  ...
end

但是这样出现了太多的双三组合。

当我像下面的代码一样使用发送参数时,'and' 方法是 运行 而不是 'or' 方法。

class Unit < ApplicationRecord
  ...
  # unit_types = ['faculties', 'departments']
  def self.send_chain(unit_types)
    unit_types.inject(self, :send)
  end
end

我该怎么办,有没有可能?

class Unit < ApplicationRecord
  UnitType.groups.each do |unit_type|
    scope ActiveSupport::Inflector.pluralize(unit_type), -> { 
      where(unit_type: unit_type)
    }
  end

  scope :by_multiple_unit_types, ->(unit_types) {
    int_unit_types =  unit_types.map { |ut| UnitType.groups.index(ut) }.join(',')
    where("unit_type IN (?)", int_unit_types)
  }
end