ruby-on-rails - Rails 5 中使用 or 方法的动态作用域
问题描述
我的单元模型的一些范围:
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
推荐阅读
- react-native - React Native:不变违规:元素类型无效:预期的字符串或类/函数但得到:未定义
- java - 使用 java 代码发送邮件在少数网络上工作,而不是在少数网络上工作?
- python-3.x - 列表中的 Keras Model.fit X 与 ndarray 错误
- java - 如何在 Spring Boot 中使用 JCS(Rest api)
- android - 如何为 Switch Navigator 设置返回按钮
- c# - 从控制器动态更改 css
- php - 在MYSQL中使用多个参数进行通配符搜索?
- c - 为什么 scanf() 函数不等我在下面的代码中最后输入 char
- node.js - 升级 Ubuntu 后会出现 Node.js 错误
- java - 不再支持 Flash 嵌入视频