Continuing from the earlier post [Rails JSON Serialized Fields](/2019/rails_json_serialized_fields/), this covers how to validate JSON serialized objects from the parent model.
Continuing from the earlier post Rails JSON Serialized Fields, this covers how to validate JSON serialized objects from the parent model.
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
class SerializedValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
return unless value.present?
value.errors.messages.each do |msg|
msg.each do |t|
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
That's it. Validations can be added to the serialized objects, just like any other model. Those objects can also be validated individually.