The original motivation for this question was to find attributes for serialization of errors. Instead, after finding no resolution to this issue by looking at the GitHub issue noted by Deefour above, we switched to ActiveRecord::Reflection to find errors to search for and serialize errors.
ActiveModel::Serializer: How to gather validation errors from a hierarchical Rails model?
-
05-03-2022 - |
質問
I have a hierarchical Rails model. When it is validated, each instance of the model has an errors
attribute that is an array of errors from validation. These errors need to be serialized into a JSON object that matches the hierarchy of the main model which generated the errors. Is there a way to leverage the ActiveModel::Serializer
code so that I can use the associations already configured in the ActiveModel::Serializer
subclasses so that I can traverse the hierarchical model and extract the errors into an object to send as JSON to the client?
Here is my hierarchical model:
class Submission < ActiveRecord::Base
has_one :precipitation
end
class Precipitation < ActiveRecord::Base
has_one :precipitation_solid
belongs_to :submission
end
class PrecipitationSolid < ActiveRecord::Base
has_many :precipitation_solid_samples
belongs_to :precipitation
end
class PrecipitationSolidSample < ActiveRecord::Base
belongs_to :precipitation_solid
end
I want to generate the following JSON when sample values are out of range
{"submission": {
"precipitation": {
"precipitation_solid": {
"precipitation_solid_samples": [
"accumulation out of range",
"accumulation out of range"
]
}
}
}
Perhaps the ActiveModel::Serializer
subclasses could do this directly. But if not, is there some way to inspect the associations defined in the serializers when I create the errors object?
解決