Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Fix `validates_uniqueness_off :field, :allow_nil => false`

Closes (#5853)

Uniqueness validator was not properly checking if there are any existing
records, when value was `nil` and column was text type. `nil` was
converted to string, which resulted in queries looking like:

```sql
SELECT 1 FROM "posts" WHERE "posts"."title" = '' LIMIT 1
```

instead of

```sql
SELECT 1 FROM "posts" WHERE "posts"."title" IS NULL LIMIT 1
```
  • Loading branch information...
commit f7d01ecf753ab8db3ba1b0a10586590b0855a31a 1 parent c520504
@drogus drogus authored
View
4 activerecord/lib/active_record/validations/uniqueness.rb
@@ -54,7 +54,7 @@ def find_finder_class_for(record) #:nodoc:
def build_relation(klass, table, attribute, value) #:nodoc:
column = klass.columns_hash[attribute.to_s]
- value = column.limit ? value.to_s.mb_chars[0, column.limit] : value.to_s if column.text?
+ value = column.limit ? value.to_s.mb_chars[0, column.limit] : value.to_s if value && column.text?
if !options[:case_sensitive] && value && column.text?
# will use SQL LOWER function before comparison, unless it detects a case insensitive collation
@@ -81,7 +81,7 @@ module ClassMethods
#
# class Person < ActiveRecord::Base
# validates_uniqueness_of :user_name, :scope => :account_id
- # end
+ # end
#
# Or even multiple scope parameters. For example, making sure that a teacher can only be on the schedule once
# per semester for a particular class.
View
11 activerecord/test/cases/validations/uniqueness_validation_test.rb
@@ -293,4 +293,15 @@ def test_validate_straight_inheritance_uniqueness
assert w6.errors[:city].any?, "Should have errors for city"
assert_equal ["has already been taken"], w6.errors[:city], "Should have uniqueness message for city"
end
+
+ def test_allow_nil_is_false
+ Topic.validates_uniqueness_of(:title, :allow_nil => false)
+ Topic.destroy_all
+
+ Topic.create!("title" => nil)
+ topic = Topic.new("title" => nil)
+ assert !topic.valid?, "topic should not be valid"
+ assert topic.errors[:title].any?, "Should have errors for title"
+ assert_equal ["has already been taken"], topic.errors[:title], "Should have uniqueness message for title"
+ end
end
Please sign in to comment.
Something went wrong with that request. Please try again.