Skip to content
This repository
Browse code

Merge pull request #4346 from pyromaniac/master

Nil values uniquines validation
  • Loading branch information...
commit 6e6764b3a1479523eb352ca2baeed0a508ce954b 2 parents 432a95d + 5a4cdf9
José Valim josevalim authored
4 activerecord/lib/active_record/validations/uniqueness.rb
@@ -52,13 +52,13 @@ def find_finder_class_for(record) #:nodoc:
52 52
53 53 def build_relation(klass, table, attribute, value) #:nodoc:
54 54 column = klass.columns_hash[attribute.to_s]
55   - value = column.limit ? value.to_s[0, column.limit] : value.to_s if column.text?
  55 + value = column.limit ? value.to_s[0, column.limit] : value.to_s if !value.nil? && column.text?
56 56
57 57 if !options[:case_sensitive] && value && column.text?
58 58 # will use SQL LOWER function before comparison, unless it detects a case insensitive collation
59 59 relation = klass.connection.case_insensitive_comparison(table, attribute, column, value)
60 60 else
61   - value = klass.connection.case_sensitive_modifier(value)
  61 + value = klass.connection.case_sensitive_modifier(value) unless value.nil?
62 62 relation = table[attribute].eq(value)
63 63 end
64 64
12 activerecord/test/cases/validations/uniqueness_validation_test.rb
@@ -45,6 +45,18 @@ def test_validate_uniqueness
45 45 assert t2.save, "Should now save t2 as unique"
46 46 end
47 47
  48 + def test_validates_uniqueness_with_nil_value
  49 + Topic.validates_uniqueness_of(:title)
  50 +
  51 + t = Topic.new("title" => nil)
  52 + assert t.save, "Should save t as unique"
  53 +
  54 + t2 = Topic.new("title" => nil)
  55 + assert !t2.valid?, "Shouldn't be valid"
  56 + assert !t2.save, "Shouldn't save t2 as unique"
  57 + assert_equal ["has already been taken"], t2.errors[:title]
  58 + end
  59 +
48 60 def test_validates_uniqueness_with_validates
49 61 Topic.validates :title, :uniqueness => true
50 62 Topic.create!('title' => 'abc')

0 comments on commit 6e6764b

Please sign in to comment.
Something went wrong with that request. Please try again.