Ability to customise the errors JSON response for nested attributes

Hello guys,

We’re working in some applications where we need to customise the JSON errors output in a more robust way (the front-end have a lot of backbone stuff).

When a active record object fails to create, rails render this response:

{
:“employments.company”=>[“can’t be blank”],
:email=>[“can’t be blank”],

:password=>[“can’t be blank”]

}

The first problem happens if you have more than one employment, first of all you won’t know which one has the error message.

There is a pull request open since Dec, 2012 proposing to improve this response to:

{
:“employments[0].company”=>[“can’t be blank”],
:“employments[1].company”=>[“can’t be blank”],

:email=>[“can’t be blank”],

:password=>[“can’t be blank”]

}

Which would allow us to at least know which child has the error.

I would to propose a better response or at least an option to do that, to have this output:

{

:employments => {

0 => { :company => ["can't be blank"] },

1 => { :company => ["can't be blank"] }

}
:email=>[“can’t be blank”],

:password=>[“can’t be blank”]

}

In this last response the errors would be easily accessible for anything on front-end like Angular, Ember.js or Backbone.

But it’s completely backwards incompatible and may break all applications that relies on the current output.

I’m not sure about the current versioning scheme of rails but in long term (rails 5?) this output would be the best.

But until then, would be great to have something like specifying a custom object to mount the errors.

I’m trying to follow where active record puts the nested validations on the errors object, seems like it put the nested errors using the dot notation and because of that we would to have to workaround it to “expand” the notation to create this last output I suggest and that’s not easy or even fast to compute.

Am I missing a way to do that or we really need to change something on active record to be able to do that? If so, where can I start?

Cheers,

Gabriel Sobrinho

gabrielsobrinho.com

The pull request I mentioned: https://github.com/rails/rails/pull/8638

Got a working prototype using a monkey patch: https://gist.github.com/sobrinho/f634f52a4ab7d47588f5

But object.errors.full_messages is not working anymore, we may need to reimplement the full_messages method.