From 112c5f18fa93b0b3b8ba55b0002515f294316829 Mon Sep 17 00:00:00 2001 From: Lawrence Pit Date: Fri, 11 Sep 2009 16:02:00 +1000 Subject: [PATCH] docs + test for each_error --- activerecord/lib/active_record/validations.rb | 12 ++++++++++++ activerecord/test/cases/validations_test.rb | 13 ++++++++++++- 2 files changed, 24 insertions(+), 1 deletions(-) diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb index 1dc7c96..f990d2e 100644 --- a/activerecord/lib/active_record/validations.rb +++ b/activerecord/lib/active_record/validations.rb @@ -242,6 +242,18 @@ module ActiveRecord @errors.each_key { |attr| @errors[attr].each { |error| yield attr, error.message } } end + # Yields each attribute and associated error per error added. + # + # class Company < ActiveRecord::Base + # validates_presence_of :name, :address, :email + # validates_length_of :name, :in => 5..30 + # end + # + # company = Company.create(:address => '123 First St.') + # company.errors.each_error{|attr,err| puts "#{attr} - #{err.type}" } + # # => name - :too_short + # # name - :blank + # # address - :blank def each_error @errors.each_key { |attr| @errors[attr].each { |error| yield attr, error } } end diff --git a/activerecord/test/cases/validations_test.rb b/activerecord/test/cases/validations_test.rb index 4c023c3..e217290 100644 --- a/activerecord/test/cases/validations_test.rb +++ b/activerecord/test/cases/validations_test.rb @@ -172,7 +172,7 @@ class ValidationsTest < ActiveRecord::TestCase end end - def test_single_error_per_attr_iteration + def test_single_error_string_per_attr_iteration r = Reply.new r.save @@ -183,6 +183,17 @@ class ValidationsTest < ActiveRecord::TestCase assert errors.include?(["content", "Empty"]) end + def test_single_error_object_per_attr_iteration + r = Reply.new + r.save + + errors = [] + r.errors.each_error { |attr, error| errors << [attr, error.attribute] } + + assert errors.include?(["title", "title"]) + assert errors.include?(["content", "content"]) + end + def test_multiple_errors_per_attr_iteration_with_full_error_composition r = Reply.new r.title = "Wrong Create" -- 1.5.5.1