aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record
diff options
context:
space:
mode:
authorDavid Heinemeier Hansson <david@loudthinking.com>2004-12-22 23:40:44 +0000
committerDavid Heinemeier Hansson <david@loudthinking.com>2004-12-22 23:40:44 +0000
commitab4c640b96f1bf1882f78847d0357e7492b621b1 (patch)
tree4b13433c1c00f73c6a51afc0dfc32f861b65a3da /activerecord/lib/active_record
parentd834b65b540665db81cca51fdc828d0c91e314a6 (diff)
downloadrails-ab4c640b96f1bf1882f78847d0357e7492b621b1.tar.gz
rails-ab4c640b96f1bf1882f78847d0357e7492b621b1.tar.bz2
rails-ab4c640b96f1bf1882f78847d0357e7492b621b1.zip
Added scope option to validation_uniqueness #349 [Kent Sibilev]
git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@259 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
Diffstat (limited to 'activerecord/lib/active_record')
-rwxr-xr-xactiverecord/lib/active_record/validations.rb9
1 files changed, 7 insertions, 2 deletions
diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb
index 1a4d6c190f..1d0dd68df8 100755
--- a/activerecord/lib/active_record/validations.rb
+++ b/activerecord/lib/active_record/validations.rb
@@ -198,7 +198,7 @@ module ActiveRecord
# can be named "davidhh".
#
# class Person < ActiveRecord::Base
- # validates_uniqueness_of :user_name
+ # validates_uniqueness_of :user_name, :scope => "account_id"
# end
#
# When the record is created, a check is performed to make sure that no record exist in the database with the given value for the specified
@@ -206,12 +206,17 @@ module ActiveRecord
#
# Configuration options:
# * <tt>message</tt> - Specifies a custom error message (default is: "has already been taken")
+ # * <tt>scope</tt> - Ensures that the uniqueness is restricted to a condition of "scope = record.scope"
def validates_uniqueness_of(*attr_names)
configuration = { :message => ActiveRecord::Errors.default_error_messages[:taken] }
configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)
for attr_name in attr_names
- class_eval(%(validate %{errors.add("#{attr_name}", "#{configuration[:message]}") if self.class.find_first(new_record? ? ["#{attr_name} = ?", #{attr_name}] : ["#{attr_name} = ? AND id <> ?", #{attr_name}, id])}))
+ if scope = configuration[:scope]
+ class_eval(%(validate %{errors.add('#{attr_name}', '#{configuration[:message]}') if self.class.find_first(new_record? ? ['#{attr_name} = ? AND #{scope} = ?', #{attr_name}, #{scope}] : ["#{attr_name} = ? AND id <> ? AND #{scope} = ?", #{attr_name}, id, #{scope}])}))
+ else
+ class_eval(%(validate %{errors.add('#{attr_name}', '#{configuration[:message]}') if self.class.find_first(new_record? ? ['#{attr_name} = ?', #{attr_name}] : ["#{attr_name} = ? AND id <> ?", #{attr_name}, id])}))
+ end
end
end