Skip to content

Commit

Permalink
Fix validation on uniqueness of empty association
Browse files Browse the repository at this point in the history
  • Loading branch information
exAspArk committed Nov 22, 2013
1 parent 34c08d2 commit c449a74
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
4 changes: 4 additions & 0 deletions activerecord/CHANGELOG.md
Original file line number Original file line Diff line number Diff line change
@@ -1,3 +1,7 @@
* Fix validation on uniqueness of empty association.

*Evgeny Li*

* Make `ActiveRecord::Relation#unscope` affect relations it is merged in to. * Make `ActiveRecord::Relation#unscope` affect relations it is merged in to.


*Jon Leighton* *Jon Leighton*
Expand Down
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/validations/uniqueness.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def find_finder_class_for(record) #:nodoc:
def build_relation(klass, table, attribute, value) #:nodoc: def build_relation(klass, table, attribute, value) #:nodoc:
if reflection = klass.reflect_on_association(attribute) if reflection = klass.reflect_on_association(attribute)
attribute = reflection.foreign_key attribute = reflection.foreign_key
value = value.attributes[reflection.primary_key_column.name] value = value.attributes[reflection.primary_key_column.name] unless value.nil?
end end


column = klass.columns_hash[attribute.to_s] column = klass.columns_hash[attribute.to_s]
Expand Down
19 changes: 19 additions & 0 deletions activerecord/test/cases/validations/uniqueness_validation_test.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ class Employee < ActiveRecord::Base
validates_uniqueness_of :nicknames validates_uniqueness_of :nicknames
end end


class TopicWithUniqEvent < Topic
belongs_to :event, foreign_key: :parent_id
validates :event, uniqueness: true
end

class UniquenessValidationTest < ActiveRecord::TestCase class UniquenessValidationTest < ActiveRecord::TestCase
fixtures :topics, 'warehouse-things', :developers fixtures :topics, 'warehouse-things', :developers


Expand Down Expand Up @@ -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" assert_equal ["has already been taken"], e2.errors[:nicknames], "Should have uniqueness message for nicknames"
end end
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 end

0 comments on commit c449a74

Please sign in to comment.