rails/rails — pull request #9364 by wangjohn (2013-02-21 19:12:50+00:00)
Title: Creating validations for nested associations. 

I'm fixing issue https://github.com/rails/rails/issues/4568. I'm using the test's from the PR that @jeyb wrote in https://github.com/rails/rails/pull/8308. However, his solution is not quite correct because there are some edge cases which cause his solution to fail (in particular any uniqueness validation with scopes).

*The Problem:*

The reason why this had to be solved with a bunch of code is because (at least to my knowledge) there's currently no way to check the uniqueness of a collection of new objects that have not yet been saved.

The basic problem is that we have a bunch of new objects in our association, so when we check to see if they are valid one by one, each of the uniqueness validations pass. However, if two objects in the collection should fail a uniqueness validation (maybe two objects in the collection are exactly the same) we'd never know. We need to introduce some way to validate uniqueness across an unpersisted collection of records.

*My Solution:*

My solution is to add a new method which checks uniqueness in a collection which has not yet been persisted. This only is called after all of the other validations are run and have passed (thus it is only called if records have not yet been persisted).

I found all of the uniqueness validations associated with a particular collection of records, then made sure that the collection of records doesn't break any of these uniqueness validators.