title: Mongoid + rails 4 - implementing User & Following: uniquness validation of embedded model
body: <p>I am using Rails 4.2.1 and Mongoid 4.0.0</p>
  
  <p>I have a <code>User</code> model, which embeds the <code>Following</code> model. The effect I am trying to reach is:</p>
  
  <pre><code>{
      username:  # This is the id
      ...
      followings: [
          {
              _id:
              username:
              datetime:
          }
      ]
  }
  </code></pre>
  
  <p>I do not want <code>followings</code> to contain entries with the same username. How to achieve this?</p>
  
  <p>I have tried two methods:</p>
  
  <ol>
  <li><p>I put <code>validates :username, presence: true, uniqueness: true</code> in the code for <code>Following</code> model. But this validation is global - If I have John and Sam as two users, and John follows Sam, then when Sam wants to follow John, there is an error of duplication.</p></li>
  <li><p>I added an index in the <code>User</code> model:</p>
  
  <p><code>index ({ 'followings.username': 1 }, { unique: true, drop_dups: true })</code>
  The problem with this approach is that, when I create a user John, the followings field for him will have a username <code>null</code>, and then if I create a user Sam, an error is thrown because the <code>null</code> username is duplicated:</p>
  
  <p><code>E11000 duplicate key error index: myapp_development.users.$followings.username_1  dup key: { : null }</code></p></li>
  </ol>
  
  <p>Really appreciate any help</p>