title: Rails HABTM: Post.title uniqueness per User only
body: <p>In Rails 4, I have a typical HABTM setup;</p>
  
  <pre><code>class Author &lt; ActiveRecord::Base
    has_and_belongs_to_many :posts
  end
  
  class Post &lt; ActiveRecord::Base
    has_and_belongs_to_many :authors
  end
  </code></pre>
  
  <p>I'm wanting to validate the uniqueness of <code>Post.title</code>, but only on a per <code>Author</code> basis. So;</p>
  
  <ul>
  <li>Author #1 can have Post.title 'My Post'</li>
  <li>Author #2 can have Post.title 'My Post'</li>
  <li>but, Author #1 can not create a second Post with title 'My Post'</li>
  </ul>
  
  <p>A <code>Post</code> is allowed to have more than one <code>Author</code> so I can't just have a <code>belongs_to</code> and use <code>validates_uniqueness_of :title, scope: :author_id</code> and I'm not sure how best to do this with HABTM.</p>
  
  <p>Is this possible with a <code>validates</code> or would I need a <code>callback</code> that first checks if the associated <code>Author</code> has a matching <code>Post.title</code> before saving?</p>
  
  <hr/>
  
  <p><strong>EDIT</strong></p>
  
  <p>I used the following migration to set up the join table;</p>
  
  <pre><code>class CreateAuthorsPosts &lt; ActiveRecord::Migration
    def change
      create_table :authors_posts, id: false, force: true do |t|
        t.belongs_to :author, index: true
        t.belongs_to :post, index: true
      end
      add_index :authors_posts, [:author_id, :post_id], unique: true
    end
  end
  </code></pre>