From 179c2ed2df1b8e7fb1163ca9bc4aafbd5e8c818d Mon Sep 17 00:00:00 2001 From: Adam Meehan Date: Sat, 11 Sep 2010 19:53:36 +1000 Subject: [PATCH] convert ActiveModel::Errors to plain OrderedHash in serialization to properly handle multiple errors per attribute --- activemodel/lib/active_model/errors.rb | 4 +++- .../serializeration/json_serialization_test.rb | 15 ++++++++------- activemodel/test/cases/validations_test.rb | 4 ++-- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb index e9a61da..8b72488 100644 --- a/activemodel/lib/active_model/errors.rb +++ b/activemodel/lib/active_model/errors.rb @@ -165,7 +165,9 @@ module ActiveModel # Returns an ActiveSupport::OrderedHash that can be used as the JSON representation for this object. def as_json(options=nil) - self + hash = ActiveSupport::OrderedHash.new + each { |k, v| (hash[k] ||= []) << v } + hash end # Adds +message+ to the error messages on +attribute+, which will be returned on a call to diff --git a/activemodel/test/cases/serializeration/json_serialization_test.rb b/activemodel/test/cases/serializeration/json_serialization_test.rb index 20d123e..500a5c5 100644 --- a/activemodel/test/cases/serializeration/json_serialization_test.rb +++ b/activemodel/test/cases/serializeration/json_serialization_test.rb @@ -6,6 +6,7 @@ require 'active_support/core_ext/object/instance_variables' class Contact extend ActiveModel::Naming include ActiveModel::Serializers::JSON + include ActiveModel::Validations def attributes instance_values @@ -105,15 +106,15 @@ class JsonSerializationTest < ActiveModel::TestCase end test "should return OrderedHash for errors" do - car = Automobile.new - - # run the validation - car.valid? + contact = Contact.new + contact.errors.add :name, "can't be blank" + contact.errors.add :name, "is too short (minimum is 2 characters)" + contact.errors.add :age, "must be 16 or over" hash = ActiveSupport::OrderedHash.new - hash[:make] = "can't be blank" - hash[:model] = "is too short (minimum is 2 characters)" - assert_equal hash.to_json, car.errors.to_json + hash[:name] = ["can't be blank", "is too short (minimum is 2 characters)"] + hash[:age] = ["must be 16 or over"] + assert_equal hash.to_json, contact.errors.to_json end test "serializable_hash should not modify options passed in argument" do diff --git a/activemodel/test/cases/validations_test.rb b/activemodel/test/cases/validations_test.rb index 4024002..55b477d 100644 --- a/activemodel/test/cases/validations_test.rb +++ b/activemodel/test/cases/validations_test.rb @@ -174,8 +174,8 @@ class ValidationsTest < ActiveModel::TestCase assert_match %r{Content can't be blank}, xml hash = ActiveSupport::OrderedHash.new - hash[:title] = "can't be blank" - hash[:content] = "can't be blank" + hash[:title] = ["can't be blank"] + hash[:content] = ["can't be blank"] assert_equal t.errors.to_json, hash.to_json end -- 1.6.5