How to validate uniqueness in json?

Viewed 707

How can i validate name field in my User class?

example:

User.create(name: { en: "name", ka: "1" }) // => ok
User.create(name: { en: "name", ka: "2" }) // => error

Here is class:

class User < ApplicationRecord
  validates :name, presence: true, json: { schema: NAME_SCHEMA }
end

here is name schema:

{
  "type": "object",
  "properties": {
    "en": {
      "type": "string",
      "maxLength": 150
    },
    "ka": {
      "type": "string",
      "maxLength": 150
    }
  }
}
1 Answers

I believe there is no built-in validator for this. But it is quite easy to write it:

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
Related