Skip to content
This repository
Browse code

docs + test for each_error

[#3185 state:committed]

Signed-off-by: Jeremy Kemper <jeremy@bitsweat.net>
  • Loading branch information...
commit 0706bdce603897a869b9af753fddb81a9c9dc7ec 1 parent 5d7ad7b
Lawrence Pit authored September 11, 2009 jeremy committed May 15, 2010
12  activerecord/lib/active_record/validations.rb
@@ -239,6 +239,18 @@ def each
239 239
       @errors.each_key { |attr| @errors[attr].each { |error| yield attr, error.message } }
240 240
     end
241 241
 
  242
+    # Yields each attribute and associated error per error added.
  243
+    #
  244
+    #   class Company < ActiveRecord::Base
  245
+    #     validates_presence_of :name, :address, :email
  246
+    #     validates_length_of :name, :in => 5..30
  247
+    #   end
  248
+    #
  249
+    #   company = Company.create(:address => '123 First St.')
  250
+    #   company.errors.each_error{|attr,err| puts "#{attr} - #{err.type}" }
  251
+    #   # => name - :too_short
  252
+    #   #    name - :blank
  253
+    #   #    address - :blank
242 254
     def each_error
243 255
       @errors.each_key { |attr| @errors[attr].each { |error| yield attr, error } }
244 256
     end
13  activerecord/test/cases/validations_test.rb
@@ -188,7 +188,7 @@ def test_values_are_not_retrieved_unless_needed
188 188
     end
189 189
   end
190 190
 
191  
-  def test_single_error_per_attr_iteration
  191
+  def test_single_error_string_per_attr_iteration
192 192
     r = Reply.new
193 193
     r.save
194 194
 
@@ -199,6 +199,17 @@ def test_single_error_per_attr_iteration
199 199
     assert errors.include?(["content", "Empty"])
200 200
   end
201 201
 
  202
+  def test_single_error_object_per_attr_iteration
  203
+    r = Reply.new
  204
+    r.save
  205
+
  206
+    errors = []
  207
+    r.errors.each_error { |attr, error| errors << [attr, error.attribute] }
  208
+
  209
+    assert errors.include?(["title", "title"])
  210
+    assert errors.include?(["content", "content"])
  211
+  end
  212
+
202 213
   def test_multiple_errors_per_attr_iteration_with_full_error_composition
203 214
     r = Reply.new
204 215
     r.title   = "Wrong Create"

0 notes on commit 0706bdc

Please sign in to comment.
Something went wrong with that request. Please try again.