aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord
diff options
context:
space:
mode:
authorDan Pickett <dpickett@enlightsolutions.com>2012-01-06 19:17:36 -0500
committerDan Pickett <dpickett@enlightsolutions.com>2012-01-06 19:17:36 -0500
commit3b5fbafab014325bdd42a7cae867ee5c92bc3298 (patch)
tree2c2c79e39c61bfdfb7c9e951a45b2aea7dfd46fd /activerecord
parent5f472785fed770da77270300fb9ee5d7763ba7ac (diff)
downloadrails-3b5fbafab014325bdd42a7cae867ee5c92bc3298.tar.gz
rails-3b5fbafab014325bdd42a7cae867ee5c92bc3298.tar.bz2
rails-3b5fbafab014325bdd42a7cae867ee5c92bc3298.zip
allow association as 1st uniqueness validation arg
#4321
Diffstat (limited to 'activerecord')
-rw-r--r--activerecord/lib/active_record/validations/uniqueness.rb10
-rw-r--r--activerecord/test/cases/validations/uniqueness_validation_test.rb12
2 files changed, 21 insertions, 1 deletions
diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb
index 77ddd72e59..3a741ba600 100644
--- a/activerecord/lib/active_record/validations/uniqueness.rb
+++ b/activerecord/lib/active_record/validations/uniqueness.rb
@@ -56,7 +56,15 @@ module ActiveRecord
end
def build_relation(klass, table, attribute, value) #:nodoc:
- column = klass.columns_hash[attribute.to_s]
+ reflection = klass.reflect_on_association(attribute)
+ column = nil
+ if(reflection)
+ column = klass.columns_hash[reflection.foreign_key]
+ attribute = reflection.foreign_key
+ value = value.attributes[reflection.primary_key_column.name]
+ else
+ column = klass.columns_hash[attribute.to_s]
+ end
value = column.limit ? value.to_s[0, column.limit] : value.to_s if !value.nil? && column.text?
if !options[:case_sensitive] && value && column.text?
diff --git a/activerecord/test/cases/validations/uniqueness_validation_test.rb b/activerecord/test/cases/validations/uniqueness_validation_test.rb
index 44c2812bff..79442d68b0 100644
--- a/activerecord/test/cases/validations/uniqueness_validation_test.rb
+++ b/activerecord/test/cases/validations/uniqueness_validation_test.rb
@@ -104,6 +104,18 @@ class UniquenessValidationTest < ActiveRecord::TestCase
assert !r2.valid?, "Saving r2 first time"
end
+ def test_validate_uniqueness_with_object_arg
+ Reply.validates_uniqueness_of(:topic)
+
+ t = Topic.create("title" => "I'm unique!")
+
+ r1 = t.replies.create "title" => "r1", "content" => "hello world"
+ assert r1.valid?, "Saving r1"
+
+ r2 = t.replies.create "title" => "r2", "content" => "hello world"
+ assert !r2.valid?, "Saving r2 first time"
+ end
+
def test_validate_uniqueness_scoped_to_defining_class
t = Topic.create("title" => "What, me worry?")