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
class Precipitation < ActiveRecord::Base
class PrecipitationSolid < ActiveRecord::Base
class PrecipitationSolidSample < ActiveRecord::Base
I want to generate the following JSON when sample values are out of range
"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?
I have a feeling that deep associations are an antipattern, so I'm not sure how to do this, and I'm not sure we'll implement it if it doesn't Just Work already. But I'll give it some thought and leave this open until that's decided.
I agree that attempting to save a tree-full of deep associations is a really Bad Time™, but I've had several clients in the past for whom moving to fat-client JS was made extra cumbersome b/c it's very hard to get back well-structured nested validation errors as JSON.
Sometimes both server-side validation is necessary and data integrity is at risk when inserting the root of an object graph before the children or grandchildren have been validly created. It can probably always be designed-around at a lower level, but I've run into several Rails apps that hit this issue.
That said, I have no insight into how feasible it is to add structured validation responses to AMS.
Closing in favor of json-api/json-api#7
Here is a dirty hack with ActiveRecord::Base.reflect_on_all_association if anyone interrested