Skip to content

Commit aeaab06

Browse files
sr3djosevalim
authored andcommitted
ActiveModel::Errors json serialization to work as Rails 3b4 [rails#5254 state:resolved]
Signed-off-by: José Valim <[email protected]>
1 parent 59cf514 commit aeaab06

File tree

3 files changed

+22
-6
lines changed

3 files changed

+22
-6
lines changed

activemodel/lib/active_model/errors.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -169,9 +169,9 @@ def to_xml(options={})
169169
to_a.to_xml options.reverse_merge(:root => "errors", :skip_types => true)
170170
end
171171

172-
# Returns an array as JSON representation for this object.
172+
# Returns an ActiveSupport::OrderedHash that can be used as the JSON representation for this object.
173173
def as_json(options=nil)
174-
to_a
174+
self
175175
end
176176

177177
# Adds +message+ to the error messages on +attribute+, which will be returned on a call to

activemodel/test/cases/serializeration/json_serialization_test.rb

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ def setup
8989
assert_match %r{"preferences":\{"shows":"anime"\}}, json
9090
end
9191

92-
test "methds are called on object" do
92+
test "methods are called on object" do
9393
# Define methods on fixture.
9494
def @contact.label; "Has cheezburger"; end
9595
def @contact.favorite_quote; "Constraints are liberating"; end
@@ -102,4 +102,18 @@ def @contact.favorite_quote; "Constraints are liberating"; end
102102
assert_match %r{"label":"Has cheezburger"}, methods_json
103103
assert_match %r{"favorite_quote":"Constraints are liberating"}, methods_json
104104
end
105+
106+
test "should return OrderedHash for errors" do
107+
car = Automobile.new
108+
109+
# run the validation
110+
car.valid?
111+
112+
hash = ActiveSupport::OrderedHash.new
113+
hash[:make] = "can't be blank"
114+
hash[:model] = "is too short (minimum is 2 characters)"
115+
assert_equal hash.to_json, car.errors.to_json
116+
end
117+
118+
105119
end

activemodel/test/cases/validations_test.rb

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -170,9 +170,11 @@ def test_errors_conversions
170170
assert_match %r{<errors>}, xml
171171
assert_match %r{<error>Title can't be blank</error>}, xml
172172
assert_match %r{<error>Content can't be blank</error>}, xml
173-
174-
json = t.errors.to_json
175-
assert_equal t.errors.to_a.to_json, json
173+
174+
hash = ActiveSupport::OrderedHash.new
175+
hash[:title] = "can't be blank"
176+
hash[:content] = "can't be blank"
177+
assert_equal t.errors.to_json, hash.to_json
176178
end
177179

178180
def test_validation_order

0 commit comments

Comments
 (0)