首页 > 解决方案 > 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

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

标签: ruby-on-railsruby-on-rails-5.2

解决方案


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

推荐阅读