1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Ensure validates_uniqueness_of considers limit on the field. [#1042 state:resolved]

Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
This commit is contained in:
Arthur Klepchukov 2009-03-07 13:52:17 +00:00 committed by Pratik Naik
parent f36513653f
commit ccb0a92fa2
4 changed files with 20 additions and 4 deletions

View file

@ -720,20 +720,20 @@ module ActiveRecord
# class (which has a database table to query from).
finder_class = class_hierarchy.detect { |klass| !klass.abstract_class? }
is_text_column = finder_class.columns_hash[attr_name.to_s].text?
column = finder_class.columns_hash[attr_name.to_s]
if value.nil?
comparison_operator = "IS ?"
elsif is_text_column
elsif column.text?
comparison_operator = "#{connection.case_sensitive_equality_operator} ?"
value = value.to_s
value = column.limit ? value.to_s[0, column.limit] : value.to_s
else
comparison_operator = "= ?"
end
sql_attribute = "#{record.class.quoted_table_name}.#{connection.quote_column_name(attr_name)}"
if value.nil? || (configuration[:case_sensitive] || !is_text_column)
if value.nil? || (configuration[:case_sensitive] || !column.text?)
condition_sql = "#{sql_attribute} #{comparison_operator}"
condition_params = [value]
else

View file

@ -8,6 +8,7 @@ require 'models/warehouse_thing'
require 'models/guid'
require 'models/owner'
require 'models/pet'
require 'models/event'
# The following methods in Topic are used in test_conditional_validation_*
class Topic
@ -530,6 +531,14 @@ class ValidationsTest < ActiveRecord::TestCase
end
end
def test_validate_uniqueness_with_limit
# Event.title is limited to 5 characters
e1 = Event.create(:title => "abcde")
assert e1.valid?, "Could not create an event with a unique, 5 character title"
e2 = Event.create(:title => "abcdefgh")
assert !e2.valid?, "Created an event whose title, with limit taken into account, is not unique"
end
def test_validate_straight_inheritance_uniqueness
w1 = IneptWizard.create(:name => "Rincewind", :city => "Ankh-Morpork")
assert w1.valid?, "Saving w1"

View file

@ -0,0 +1,3 @@
class Event < ActiveRecord::Base
validates_uniqueness_of :title
end

View file

@ -155,6 +155,10 @@ ActiveRecord::Schema.define do
t.integer :course_id, :null => false
end
create_table :events, :force => true do |t|
t.string :title, :limit => 5
end
create_table :funny_jokes, :force => true do |t|
t.string :name
end