Forum: Ruby on Rails validates_uniqueness_of (with :scope) doesn't seem to work?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
David K. (Guest)
on 2007-05-06 18:12
(Received via mailing list)
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
Eden L. (Guest)
on 2007-05-06 19:18
(Received via mailing list)
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.
This topic is locked and can not be replied to.