对数组数据类型使用什么验证

What validations to use for an array data type

PostgreSQL 将其他数据类型添加到 Active Record 默认值。
请参阅 RailsGuides 中的 PostgreSQL documentation, List of available datatypes at Whosebug and Active Record and PostgreSQL
对于 array 数据类型,需要在迁移中添加 array: true。例如:

create_table :books do |t|
  t.string 'title'
  t.string 'tags', array: true
  t.integer 'ratings', array: true
end

Book 模型应该使用什么样的验证?
如果整数是非数组数据类型,我将使用:

validates :ratings, numericality: { only_integer: true, greater_than: 0 }

如果 ratings 是数组数据类型,此验证是否也正确?
我感兴趣的是验证数组元素而不是数组本身。

据我所知,没有针对这种情况的内置验证。

您可以编写自定义的:

validate :valid_ratings

private

def valid_ratings
  if everything_is_ok
    true
  else
    errors.add(:ratings, 'ratings is invalid') if something_is_wrong
  end
end