Permalink
Browse files

allow an association as a scope parameter

  • Loading branch information...
1 parent 984ce0c commit 5f472785fed770da77270300fb9ee5d7763ba7ac Dan Pickett committed Jan 6, 2012
@@ -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
@@ -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?")

0 comments on commit 5f47278

Please sign in to comment.