如何使用 Enumerize 验证数组的存在?

How to validate presence of an array using Enumerize?

我正在尝试使用 Enumerize Gem 在给定的模型类数组字段上实施验证。我想:

似乎当我提供一个包含空字符串的列表时,存在验证器失败了。请参阅此示例。

class MyModel
  include ActiveModel::Model
  extend Enumerize

  enumerize :cities, in: %w(Boston London Berlin Paris), multiple: true
  validates :cities, presence: true
end


# Does not behave as expected
a = MyModel.new(cities: [""])
a.cities.present?  # => false
a.valid?  # => true, while it should be false.

它似乎在其他一些情况下有效(例如,当您提供不在枚举中的非空字符串时)。例如

# Behaves as expected
a = MyModel.new(cities: ["Dublin"])
a.cities.present?  # => false
a.valid?  # => false

是否有解决方法可以同时使用 Enumerize 验证和 ActiveModel 存在验证?

谢谢!

enumerize gem 将您的多个值保存为字符串数组。像这样:"[\"Boston\"]"。因此,对于一个空数组,您有:"[]"presence 验证器使用 blank? 方法检查值是否存在。 "[]".blank? returns false 显然。

所以,您可以尝试一些替代方案:

选项 1:

validates :cities, inclusion: { in: %w(Boston London Berlin Paris) }

选项 2:

添加自定义验证器

validate :ensure_valid_cities

def ensure_valid_cities
  errors.add(:cities, "invalid") unless cities.values.empty?
end

这实际上是一个应该在更高版本的 Enumerize 中修复的错误(参见 https://github.com/brainspec/enumerize/pull/226)。

同时,您可以使用自定义验证器作为解决方法(参见 Leantraxx 的回答)。