Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

allow an association as a scope parameter

  • Loading branch information...
commit 5f472785fed770da77270300fb9ee5d7763ba7ac 1 parent 984ce0c
Dan Pickett authored
View
5 activerecord/lib/active_record/validations/uniqueness.rb
@@ -25,6 +25,11 @@ def validate_each(record, attribute, value)
Array(options[:scope]).each do |scope_item|
scope_value = record.send(scope_item)
+ reflection = record.class.reflect_on_association(scope_item)
+ if reflection
+ scope_value = record.send(reflection.foreign_key)
+ scope_item = reflection.foreign_key
+ end
relation = relation.and(table[scope_item].eq(scope_value))
end
View
12 activerecord/test/cases/validations/uniqueness_validation_test.rb
@@ -92,6 +92,18 @@ def test_validate_uniqueness_with_scope
assert r3.valid?, "Saving r3"
end
+ def test_validate_uniqueness_with_object_scope
+ Reply.validates_uniqueness_of(:content, :scope => :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?")
Please sign in to comment.
Something went wrong with that request. Please try again.