如何验证用户类中的名称字段?
示例:
User.create(name: { en: "name", ka: "1" }) // => ok
User.create(name: { en: "name", ka: "2" }) // => error
这是课程:
class User < ApplicationRecord
validates :name, presence: true, json: { schema: NAME_SCHEMA }
end
这是名称架构:
{
"type": "object",
"properties": {
"en": {
"type": "string",
"maxLength": 150
},
"ka": {
"type": "string",
"maxLength": 150
}
}
}
答案 0 :(得分:1)
我相信没有内置的验证器。但是写起来很容易:
class JsonUniqValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
records = record.class.select(attribute)
value.keys.each do |key|
if records.any? { |record| record.public_send(attribute)[key] == value[key] }
record.errors[attribute] << options[:message] || "variant #{key} is not unique"
end
end
class Person < ApplicationRecord
validates :name, :json_uniq => true
end