From 2174405c289febfd789ec41f583b44f033e4c980 Mon Sep 17 00:00:00 2001 From: Elise Huard Date: Sat, 8 Aug 2009 23:40:08 +0200 Subject: [PATCH] validate_uniqueness with utf8 --- activerecord/lib/active_record/validations.rb | 2 +- activerecord/test/cases/validations_test.rb | 27 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletions(-) diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb index d2d12b8..7a7d0ab 100644 --- a/activerecord/lib/active_record/validations.rb +++ b/activerecord/lib/active_record/validations.rb @@ -726,7 +726,7 @@ module ActiveRecord comparison_operator = "IS ?" elsif column.text? comparison_operator = "#{connection.case_sensitive_equality_operator} ?" - value = column.limit ? value.to_s[0, column.limit] : value.to_s + value = column.limit ? value.to_s.mb_chars[0, column.limit] : value.to_s else comparison_operator = "= ?" end diff --git a/activerecord/test/cases/validations_test.rb b/activerecord/test/cases/validations_test.rb index c20f5ae..4e33430 100644 --- a/activerecord/test/cases/validations_test.rb +++ b/activerecord/test/cases/validations_test.rb @@ -360,6 +360,23 @@ class ValidationsTest < ActiveRecord::TestCase assert t2.save, "Should now save t2 as unique" end + def test_validate_uniqueness_with_utf8 + with_kcode('UTF8') do + Topic.validates_uniqueness_of(:title) + + t_utf8 = Topic.new("title" => "Я тоже уникальный!") + assert t_utf8.save, "Should save t as unique" + + t2_utf8 = Topic.new("title" => "Я тоже уникальный!") + assert !t2_utf8.valid?, "Shouldn't be valid" + assert !t2_utf8.save, "Shouldn't save t2 as unique" + assert_equal "has already been taken", t2_utf8.errors.on(:title) + + t2_utf8.title = "Я тоже " + assert t2_utf8.save, "Should now save t2 as unique" + end + end + def test_validates_uniquness_with_newline_chars Topic.validates_uniqueness_of(:title, :case_sensitive => false) @@ -539,6 +556,16 @@ class ValidationsTest < ActiveRecord::TestCase assert !e2.valid?, "Created an event whose title, with limit taken into account, is not unique" end + def test_validate_uniqueness_with_limit_and_utf8 + with_kcode('UTF8') do + # Event.title is limited to 5 characters + e1 = Event.create(:title => "一二三四五") + assert e1.valid?, "Could not create an event with a unique, 5 character title" + e2 = Event.create(:title => "一二三四五六七八") + assert !e2.valid?, "Created an event whose title, with limit taken into account, is not unique" + end + end + def test_validate_straight_inheritance_uniqueness w1 = IneptWizard.create(:name => "Rincewind", :city => "Ankh-Morpork") assert w1.valid?, "Saving w1" -- 1.5.4.5