Fix validation on uniqueness of empty association

This commit is contained in:
Evgeny Li 2013-11-05 18:36:48 +04:00
parent 34c08d2ead
commit c449a74e89
3 changed files with 24 additions and 1 deletions

View File

@ -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 File

@ -48,7 +48,7 @@ module ActiveRecord
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 File

@ -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 @@ class UniquenessValidationTest < ActiveRecord::TestCase
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