title: Rails: Why does failing validate_uniqeness still allow save?
body: <p>-- Question rewritten based on further testing --</p>
  
  <p>So, my app has_many Folders which belong_to Collections.
  Folders are nested, they can also belong_to another Folder.</p>
  
  <p>I want to validate uniqueness of the folder names within each collection. When I create folders at the top level this works, but when I create it in lower levels it does not work. Here are the models:</p>
  
  <pre><code>class Folder &lt; ActiveRecord::Base
    # CALLBACKS
    before_create :associate_collection
  
    # RELATIONSHIPS
    belongs_to :collection
    belongs_to :parent, :class_name =&gt; 'Folder'
    has_many :subfolders, :class_name =&gt; 'Folder', :foreign_key =&gt; :parent_id
  
    # VALIDATIONS
    validates_presence_of :name
    validates_uniqueness_of :name, :scope =&gt; :collection_id
  
    private
  
    def associate_collection
      if self.collection.nil?
      self.collection = self.parent.collection
      end
    end
  end
  
  class Collection &lt; ActiveRecord::Base
  
    # RELATIONSHIPS
    has_one :root_folder, :class_name =&gt; 'Folder', :conditions =&gt; { :parent_id =&gt; nil }
    has_many :folders
  
    # CALLBACKS
    after_create :setup_root_folder
  
    private
  
    def setup_root_folder
      self.create_root_folder(:name=&gt;'Collection Root')
      self.save!
    end
  
  end
  </code></pre>
  
  <p>Here's an abridged example of what happens in the console:</p>
  
  <pre><code>c = Collection.new(:name=&gt;'ExampleCollection')
  #&lt;Collection id: 1&gt;
  
  root = c.root_folder
  #&lt;Folder id: 1, collection_id: 1&gt;
  
  f1 = root.subfolders.create(:name=&gt;'Test')
  #&lt;Folder id: 2 collection_id: 1&gt; 
  
  f1.valid?
  # TRUE
  
  f2 = root.subfolders.create(:name=&gt;'Test')
  #&lt;Folder id: 3 collection_id: 1&gt;
  
  f2.valid?
  # FALSE
  
  f1.valid?
  # FALSE
  </code></pre>
  
  <p>So, while the collection is being associated with a subfolder correctly, its not triggering the validations correctly until after it's saved.</p>
  
  <p>Suggestions?</p>