首页 > 解决方案 > rails ActiveModel::Validations 中的数据类型验证

问题描述

我想根据其数据类型验证类属性。

我正在用 ruby​​ 编写一个 API,我需要检查一个特定的参数数据是否属于 String、hash、Array 等类型。

例如。我们有

class ApiValidation
  include ActiveModel::Validations
  attr_accessor :fieldName

  validates :fieldName, :presence => true 
end 

如此相似:presence => true,我想再添加一个验证,例如:datatype => :string

请建议我一些自定义验证或任何其他方法来满足我的要求。

标签: ruby-on-railsapivalidationactiverecordactivemodel

解决方案


您可以查看 dry-rb 堆栈。

https://github.com/dry-rb/dry-types ( https://dry-rb.org/gems/dry-types/1.2/ ) gem 可以完全满足您的需求。

来自文档:

Strict types will raise an error if passed an attribute of the wrong type:

class User < Dry::Struct
  attribute :name, Types::Strict::String
  attribute :age,  Types::Strict::Integer
end
User.new(name: 'Bob', age: '18')
# => Dry::Struct::Error: [User.new] "18" (String) has invalid type for :age

推荐阅读