Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Ensure validates_uniqueness_of considers limit on the field. [#1042 s…

…tate:resolved]

Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
  • Loading branch information...
commit ccb0a92fa2ba0bf7be50033090c3a861e6d907be 1 parent f365136
@avk avk authored lifo committed
View
8 activerecord/lib/active_record/validations.rb
@@ -720,20 +720,20 @@ def validates_uniqueness_of(*attr_names)
# 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
9 activerecord/test/cases/validations_test.rb
@@ -8,6 +8,7 @@
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 @@ def test_validate_uniqueness_with_columns_which_are_sql_keywords
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
3  activerecord/test/models/event.rb
@@ -0,0 +1,3 @@
+class Event < ActiveRecord::Base
+ validates_uniqueness_of :title
+end
View
4 activerecord/test/schema/schema.rb
@@ -155,6 +155,10 @@ def create_table(*args, &block)
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
Please sign in to comment.
Something went wrong with that request. Please try again.