Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge pull request #12774 from exAspArk/fix_uniqueness_on_relation

Fix validation on uniqueness
  • Loading branch information...
commit 818b362c1db0b1103d6489dbd6f1f56e645a34e3 2 parents 34c08d2 + c449a74
@senny senny authored
4 activerecord/CHANGELOG.md
@@ -1,3 +1,7 @@
+* Fix validation on uniqueness of empty association.
+
+ *Evgeny Li*
+
* Make `ActiveRecord::Relation#unscope` affect relations it is merged in to.
*Jon Leighton*
View
2  activerecord/lib/active_record/validations/uniqueness.rb
@@ -48,7 +48,7 @@ def find_finder_class_for(record) #:nodoc:
def build_relation(klass, table, attribute, value) #:nodoc:
if reflection = klass.reflect_on_association(attribute)
attribute = reflection.foreign_key
- value = value.attributes[reflection.primary_key_column.name]
+ value = value.attributes[reflection.primary_key_column.name] unless value.nil?
end
column = klass.columns_hash[attribute.to_s]
View
19 activerecord/test/cases/validations/uniqueness_validation_test.rb
@@ -35,6 +35,11 @@ class Employee < ActiveRecord::Base
validates_uniqueness_of :nicknames
end
+class TopicWithUniqEvent < Topic
+ belongs_to :event, foreign_key: :parent_id
+ validates :event, uniqueness: true
+end
+
class UniquenessValidationTest < ActiveRecord::TestCase
fixtures :topics, 'warehouse-things', :developers
@@ -376,4 +381,18 @@ def test_validate_uniqueness_with_array_column
assert_equal ["has already been taken"], e2.errors[:nicknames], "Should have uniqueness message for nicknames"
end
end
+
+ def test_validate_uniqueness_on_existing_relation
+ event = Event.create
+ assert TopicWithUniqEvent.create(event: event).valid?
+
+ topic = TopicWithUniqEvent.new(event: event)
+ assert_not topic.valid?
+ assert_equal ['has already been taken'], topic.errors[:event]
+ end
+
+ def test_validate_uniqueness_on_empty_relation
+ topic = TopicWithUniqEvent.new
+ assert topic.valid?
+ end
end
Please sign in to comment.
Something went wrong with that request. Please try again.