| | 86 | |
|---|
| | 87 | # Patch to ActiveRecord::Validations::ClassMethods#validates_uniqueness_of. |
|---|
| | 88 | # Makes the uniqueness validation work correctly with Single Table Inheritance. |
|---|
| | 89 | # See the Rails Trac: http://dev.rubyonrails.org/ticket/3833 |
|---|
| | 90 | module ActiveRecord |
|---|
| | 91 | module Validations |
|---|
| | 92 | module ClassMethods |
|---|
| | 93 | def validates_uniqueness_of(*attr_names) |
|---|
| | 94 | configuration = { :message => ActiveRecord::Errors.default_error_messages[:taken], :case_sensitive => true } |
|---|
| | 95 | configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash) |
|---|
| | 96 | |
|---|
| | 97 | validates_each(attr_names,configuration) do |record, attr_name, value| |
|---|
| | 98 | if value.nil? || (configuration[:case_sensitive] || !columns_hash[attr_name.to_s].text?) |
|---|
| | 99 | condition_sql = "#{record.class.table_name}.#{attr_name} #{attribute_condition(value)}" |
|---|
| | 100 | condition_params = [value] |
|---|
| | 101 | else |
|---|
| | 102 | condition_sql = "LOWER(#{record.class.table_name}.#{attr_name}) #{attribute_condition(value)}" |
|---|
| | 103 | condition_params = [value.downcase] |
|---|
| | 104 | end |
|---|
| | 105 | if scope = configuration[:scope] |
|---|
| | 106 | Array(scope).map do |scope_item| |
|---|
| | 107 | scope_value = record.send(scope_item) |
|---|
| | 108 | condition_sql << " AND #{record.class.table_name}.#{scope_item} #{attribute_condition(scope_value)}" |
|---|
| | 109 | condition_params << scope_value |
|---|
| | 110 | end |
|---|
| | 111 | end |
|---|
| | 112 | unless record.new_record? |
|---|
| | 113 | condition_sql << " AND #{record.class.table_name}.#{record.class.primary_key} <> ?" |
|---|
| | 114 | condition_params << record.send(:id) |
|---|
| | 115 | end |
|---|
| | 116 | if self.find(:first, :conditions => [condition_sql, *condition_params]) |
|---|
| | 117 | record.errors.add(attr_name, configuration[:message]) |
|---|
| | 118 | end |
|---|
| | 119 | end |
|---|
| | 120 | end |
|---|
| | 121 | end |
|---|
| | 122 | end |
|---|
| | 123 | end |
|---|