如何 return 将通过验证的项目列表

How to return list of items that will pass validation

我有一个 Outlet 模型,该模型具有允许多个值的包含验证,并且我希望扩展它以具有更多值。

我想知道是否可以调用一种方法来 return 我在包含验证中使用的值数组?

class Outlet < ApplicationRecord
  belongs_to :user
  has_many :comments

  validates :category, :title, :body, :urgency, :user, presence: true
  validates :title, length: { in: 1..60 }
  validates :body, length: { in: 1..1000 }
  validates :urgency, numericality: { only_integer: true, greater_than_or_equal_to: 1, less_than_or_equal_to: 10 }
  validates :category, inclusion: { in: ['vent', 'rant', 'qualm'] }
end

ActiveModel class 方法 validators_on 将 return 给定字段的所有验证器。例如:

Outlet.validators_on(:category)
#=> [#<ActiveRecord::Validations::PresenceValidator:0x007fd2350e4b88 ...>, #<ActiveModel::Validations::InclusionValidator:0x007fd23a872cd8 ...>]

它允许像这样获取包含值:

Outlet.validators_on(:category)
  .find { |validator| validator.is_a?(ActiveModel::Validations::InclusionValidator) }
  .options[:in]

它将 return 一系列选项。

但更简洁的方法是将选项提取到 class 常量:

class Outlet < ApplicationRecord
  ALLOWED_CATEGORIES = %w(vent rant qualm).freeze

  # ...

  validates :category, inclusion: { in: ALLOWED_CATEGORIES }
end

然后通过Outlet::ALLOWED_CATEGORIES

访问允许的值