Skip to content

Commit

Permalink
ActiveModel::Errors json serialization to work as Rails 3b4 [#5254 st…
Browse files Browse the repository at this point in the history
…ate:resolved]

Signed-off-by: José Valim <jose.valim@gmail.com>
  • Loading branch information
sr3d authored and josevalim committed Aug 2, 2010
1 parent 59cf514 commit aeaab06
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 6 deletions.
4 changes: 2 additions & 2 deletions activemodel/lib/active_model/errors.rb
Expand Up @@ -169,9 +169,9 @@ def to_xml(options={})
to_a.to_xml options.reverse_merge(:root => "errors", :skip_types => true)
end

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

# Adds +message+ to the error messages on +attribute+, which will be returned on a call to
Expand Down
Expand Up @@ -89,7 +89,7 @@ def setup
assert_match %r{"preferences":\{"shows":"anime"\}}, json
end

test "methds are called on object" do
test "methods are called on object" do
# Define methods on fixture.
def @contact.label; "Has cheezburger"; end
def @contact.favorite_quote; "Constraints are liberating"; end
Expand All @@ -102,4 +102,18 @@ def @contact.favorite_quote; "Constraints are liberating"; end
assert_match %r{"label":"Has cheezburger"}, methods_json
assert_match %r{"favorite_quote":"Constraints are liberating"}, methods_json
end

test "should return OrderedHash for errors" do
car = Automobile.new

# run the validation
car.valid?

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
end


end
8 changes: 5 additions & 3 deletions activemodel/test/cases/validations_test.rb
Expand Up @@ -170,9 +170,11 @@ def test_errors_conversions
assert_match %r{<errors>}, xml
assert_match %r{<error>Title can't be blank</error>}, xml
assert_match %r{<error>Content can't be blank</error>}, xml

json = t.errors.to_json
assert_equal t.errors.to_a.to_json, json

hash = ActiveSupport::OrderedHash.new
hash[:title] = "can't be blank"
hash[:content] = "can't be blank"
assert_equal t.errors.to_json, hash.to_json
end

def test_validation_order
Expand Down

0 comments on commit aeaab06

Please sign in to comment.