title: Rails what's difference in unique index and validates_uniqueness_of
body: <p>Firstly, can anyone explain how unique index works in databases?</p>
  
  <p>Suppose I have a User model with a <code>name column</code> and I add a <code>unique index</code> on it but in the model (user.rb) I just have a <code>presence</code> validator on the <code>name</code> field.</p>
  
  <p>So now when I'm trying to create two users with same name, I get PGError  </p>
  
  <blockquote>
    <p>duplicate key value violates unique constraint "index_users_on_name"  </p>
  </blockquote>
  
  <p>So It looks to me like the <code>unique index</code> working same as <code>uniqueness validator</code>(?)  </p>
  
  <p>If so then what about foreign keys?</p>
  
  <p>Lets say I have <code>Post</code> model with <code>belongs_to :user</code> association with <code>User has_many :posts</code>.
  And a foreign key <code>user_id</code> in the <code>posts table</code> with unique index. Then multiple posts cannot have a same <code>user_id</code>. </p>
  
  <p>Can someone explain how <code>unique index</code> works?  </p>
  
  <p>I'm on Rails 4 with Ruby 2.0.0.  </p>