Permalink
Browse files

Fix validation on uniqueness of empty association

  • Loading branch information...
1 parent 34c08d2 commit c449a74e8944eed75453963288ea7a8652f5ba93 @exAspArk exAspArk committed Nov 5, 2013
@@ -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*
@@ -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]
@@ -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

0 comments on commit c449a74

Please sign in to comment.