title: How to enforce unique embedded document in mongoid
body: <p>I have the following model</p>
  
  <pre><code>class Person 
    include Mongoid::Document
    embeds_many :tasks
  end
  
  class Task
    include Mongoid::Document
    embedded_in :commit, :inverse_of =&gt; :tasks
    field :name
  end
  </code></pre>
  
  <p>How can I ensure the following?</p>
  
  <pre><code>person.tasks.create :name =&gt; "create facebook killer"
  person.tasks.create :name =&gt; "create facebook killer"
  
  person.tasks.count == 1
  
  different_person.tasks.create :name =&gt; "create facebook killer"
  person.tasks.count == 1
  different_person.tasks.count == 1
  </code></pre>
  
  <p>i.e. task names are unique within a particular person</p>
  
  <hr>
  
  <p>Having checked out the docs on indexes I thought the following might work:</p>
  
  <pre><code>class Person 
    include Mongoid::Document
    embeds_many :tasks
  
    index [
        ["tasks.name", Mongo::ASCENDING], 
        ["_id", Mongo::ASCENDING]
    ], :unique =&gt; true
  end
  </code></pre>
  
  <p>but </p>
  
  <pre><code>person.tasks.create :name =&gt; "create facebook killer"
  person.tasks.create :name =&gt; "create facebook killer"
  </code></pre>
  
  <p>still produces a duplicate.</p>
  
  <hr>
  
  <p>The index config shown above in Person would translate into for mongodb</p>
  
  <pre><code>db.things.ensureIndex({firstname : 1, 'tasks.name' : 1}, {unique : true})
  </code></pre>