Skip to content
Browse files

Fix bug with presence validation of associations.

Would incorrectly add duplicated errors when the association was blank. Bug introduced in 1fab518.
  • Loading branch information...
1 parent c432c74 commit 25262bc280e8c9c0e875315958f82230b67cbf35 @scottwillson scottwillson committed Oct 16, 2012
View
5 activerecord/CHANGELOG.md
@@ -1,5 +1,10 @@
## Rails 4.0.0 (unreleased) ##
+* Fix bug with presence validation of associations. Would incorrectly add duplicated errors
+ when the association was blank. Bug introduced in 1fab518c6a75dac5773654646eb724a59741bc13.
+
+ *Scott Willson*
+
* Fix bug where sum(expression) returns string '0' for no matching records
Fixes #7439
View
6 activerecord/lib/active_record/validations/presence.rb
@@ -5,8 +5,10 @@ def validate(record)
super
attributes.each do |attribute|
next unless record.class.reflect_on_association(attribute)
- value = record.send(attribute)
- if Array(value).all? { |r| r.marked_for_destruction? }
+ associated_records = Array(record.send(attribute))
+
+ # Superclass validates presence. Ensure present records aren't about to be destroyed.
+ if associated_records.present? && associated_records.all? { |r| r.marked_for_destruction? }
record.errors.add(attribute, :blank, options)
end
end
View
7 activerecord/test/cases/validations/presence_validation_test.rb
@@ -18,6 +18,13 @@ def test_validates_presence_of_non_association
assert b.valid?
end
+ def test_validates_presence_of_has_one
+ Boy.validates_presence_of(:face)
+ b = Boy.new
+ assert b.invalid?, "should not be valid if has_one association missing"
+ assert_equal 1, b.errors[:face].size, "validates_presence_of should only add one error"
+ end
+
def test_validates_presence_of_has_one_marked_for_destruction
Boy.validates_presence_of(:face)
b = Boy.new

0 comments on commit 25262bc

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