This project is archived and is in readonly mode.

#5615 ✓resolved
Adam Meehan

Support multiple errors per attribute in ActiveModel Errors JSON serialization

Reported by Adam Meehan | September 11th, 2010 @ 11:13 AM | in 3.0.5

The current errors json serialization does not work for mutiple errors on a attribute. It returns duplicate keys for subsequent errors for that attribute. This of course can't work when using the JSON object.

So for example this ActiveModel errors hash

{"name" => ["can't be blank", "is too short"]}

Becomes

{"name":"can't be blank","name":"is too short"]}

The change required is to output an regular ordered hash from as_json call with the error messages as an array value. This will be serialized correctly into JSON

{"name":["can't be blank","is too short"]}

It also brings it into line with how ActiveModel returns messages for an attribute, which is now always as an array. We need to be consistent across the board.

The reason the ActiveModel::Errors subclass does not get serialized correctly is due to the each method override. It doubles up the keys for attributes with multiple errors when iterated over. I tried just calling super in the as_json method, but this doesn't work because the Hash as_json method calls map on self. Thereby causing the same issue again.

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

Referenced by

Pages