我的单位模型的某些范围:
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
但是以这种方式出现了太多的三重组合。
当我使用以下代码的send参数时,'and'方法正在运行,而不是'or'方法。
class Unit < ApplicationRecord
...
# unit_types = ['faculties', 'departments']
def self.send_chain(unit_types)
unit_types.inject(self, :send)
end
end
我该怎么办,有没有可能?
答案 0 :(得分:1)
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