Rails JSON Serialized Fields - Validations

Dusty Candland | | rails, rails6

Continuing from the earlier post Rails JSON Serialized Fields, this covers how to validate JSON serialized objects from the parent model.

Custom Validator

This sets up the validation to use on the parent models. It, calls valid? on the field and copies and errors to the parent. It allows nil values.

# /app/models/serialized_validator.rb
class SerializedValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
return unless value.present?

value.valid?
value.errors.messages.each do |msg|
msg[1].each do |t|
record.errors.add("#{attribute}_#{msg[0]}".to_sym, t)
end
end
end
end

On the parent object, add the validation. This will make sure the child objects are valid when the parent is checked.

class User < ApplicationRecord
# ...

serialize :options, Options

validates :options, serialized: true

# ...
end

That's it. Validations can be added to the serialized objects, just like any other model. Those objects can also be validated individually.


Webmentions

These are webmentions via the IndieWeb and webmention.io. Mention this post from your site: