Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

ActiveModel::Errors.to_hash returns plain OrderedHash and used in to_…

…json serialization to properly handle multiple errors per attribute

Signed-off-by: José Valim <jose.valim@gmail.com>
  • Loading branch information...
commit d321e78646e1ba0ad012900008421e0b05541b9d 1 parent 52e854e
@thilo thilo authored josevalim committed
View
8 activemodel/lib/active_model/errors.rb
@@ -167,7 +167,13 @@ def to_xml(options={})
# Returns an ActiveSupport::OrderedHash that can be used as the JSON representation for this object.
def as_json(options=nil)
- self
+ to_hash
+ end
+
+ def to_hash
+ 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
View
5 activemodel/test/cases/errors_test.rb
@@ -62,4 +62,9 @@ def self.lookup_ancestors
end
+ test 'to_hash should return an ordered hash' do
+ person = Person.new
+ person.errors.add(:name, "can not be blank")
+ assert_instance_of ActiveSupport::OrderedHash, person.errors.to_hash
+ end
end
View
15 activemodel/test/cases/serializeration/json_serialization_test.rb
@@ -6,6 +6,7 @@
class Contact
extend ActiveModel::Naming
include ActiveModel::Serializers::JSON
+ include ActiveModel::Validations
def attributes
instance_values
@@ -105,15 +106,15 @@ def @contact.favorite_quote; "Constraints are liberating"; end
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
View
4 activemodel/test/cases/validations_test.rb
@@ -174,8 +174,8 @@ def test_errors_conversions
assert_match %r{<error>Content can't be blank</error>}, 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
Please sign in to comment.
Something went wrong with that request. Please try again.