Skip to content


Subversion checkout URL

You can clone with
Download ZIP


How to gather validation errors from a hierarchical Rails model? #199

akeyglobe opened this Issue · 4 comments

4 participants


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 

class Precipitation < ActiveRecord::Base
  has_one :precipitation_solid 
  belongs_to :submission

class PrecipitationSolid < ActiveRecord::Base
  has_many :precipitation_solid_samples
  belongs_to :precipitation

class PrecipitationSolidSample < ActiveRecord::Base
  belongs_to :precipitation_solid

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?


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.

@steveklabnik steveklabnik referenced this issue in json-api/json-api

Errors? #7


Closing in favor of json-api/json-api#7


Here is a dirty hack with ActiveRecord::Base.reflect_on_all_association if anyone interrested

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.