# Validates\_uniqueness\_of (with :scope) doesn't seem to work?

**URL:** <https://www.ruby-forum.com/t/validates-uniqueness-of-with-scope-doesnt-seem-to-work/103470>\
**Category:** Rails\
**Created:** [May 6, 2007, 4:12pm UTC](https://www.ruby-forum.com/t/validates-uniqueness-of-with-scope-doesnt-seem-to-work/103470 "2007-05-06T16:12:42Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![ntk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/48db29/32.png) [@ntk](https://www.ruby-forum.com/u/ntk)\
**Post date:** [May 6, 2007, 4:12pm UTC](https://www.ruby-forum.com/t/validates-uniqueness-of-with-scope-doesnt-seem-to-work/103470/1 "2007-05-06T16:12:42Z")

</div>

I have a master record called ‘project’ and a child record called  
‘agycode’. Obviously, agycode has a project\_id FK. I wish to make the  
“descr” field unique ONLY within the ‘project\_id’ ‘scope’. Here are the  
key  
pieces of information  
Agycode fields (id, project\_id, descr)

Here’s the declaration in the Agycode.rb  
validates\_uniqueness\_of _:descr_,  
_:scope_ =\> “project\_id”

Here’s the test that SHOULDN’T pass but it does

_def_ test\_should\_fail\_duplicate\_descr  
record1 = _@project_.agycodes._new_(_:descr_ =\> “description”)  
record2 = record1  
assert record1.save, “Save Record”  
assert\_valid(record1)  
assert record2.save, “Save Record”  
assert\_valid(record2)  
_end_

By the way, do you know how one would write the opposite of  
“assert\_valid”?  
Thank you,  
David

---

<div class="post-metadata">

**Author:** ![ntk](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/48db29/32.png) [@ntk](https://www.ruby-forum.com/u/ntk)\
**Post date:** [May 6, 2007, 5:18pm UTC](https://www.ruby-forum.com/t/validates-uniqueness-of-with-scope-doesnt-seem-to-work/103470/2 "2007-05-06T17:18:48Z")

</div>

You’re saving the same record twice.

The problem line: record2 = record1

This does _not_ do a “deep copy” of record1’s attributes and create a  
new object. Instead it just creates a new variable with a reference  
to the same object that record1 references.

Try: record2 = record1.clone

Note that “clone” doesn’t copy associations.
