Permalink
Browse files

Merge pull request #12774 from exAspArk/fix_uniqueness_on_relation

Fix validation on uniqueness
Conflicts:
	activerecord/CHANGELOG.md
  • Loading branch information...
1 parent f214896 commit e8458d08a88d175c067c19937893a2193e61699d @senny senny committed Nov 22, 2013
@@ -1,3 +1,7 @@
+* Fix validation on uniqueness of empty association.
+
+ *Evgeny Li*
+
* Perform necessary deeper encoding when hstore is inside an array.
Fixes #11135.
@@ -53,7 +53,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
attribute_name = attribute.to_s
@@ -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
@@ -384,4 +389,18 @@ def test_validate_uniqueness_with_array_column
assert e2.errors[:nicknames].any?, "Should have errors for nicknames"
assert_equal ["has already been taken"], e2.errors[:nicknames], "Should have uniqueness message for nicknames"
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

0 comments on commit e8458d0

Please sign in to comment.