Validate uniqueness of name in a HABTM association <p>I have an <code>Artist</code> model that has many <code>Album</code>s in a HABTM association. Though I would like to permit two different albums to have the same name I'd like to ensure that there aren't two in the collection of one artist. So far example:</p> <pre><code>artist_1 = Artist.create(name: "Jay-Z") artist_2 = Artist.create(name: "The Beatles") album_1 = Album.create(name: "The Black Album", artist_ids: [1]) album_2 = Album.create(name: "The Black Album", artist_ids: [1]) =&gt; Should return error album_2 = Album.create(name: "The Black Album", artist_ids: [2]) =&gt; Should not return an error </code></pre> <p>I first thought of validating the uniqueness of the name in the <code>Album</code> model but get this error when I try to create a new object:</p> <pre><code>SQLite3::SQLException: no such column: albums.artist_id: SELECT 1 AS one FROM "albums" WHERE ("albums"."name" = 'The Black Album' AND "albums"."artist_id" IS NULL) LIMIT 1 </code></pre> <p>I then thought of putting the validation in my join model, <code>AlbumArtist</code> but get the error <code>undefined method 'name'</code> (<code>name</code> is one of the album's attributes):</p> <pre><code>undefined method `name' for #&lt;AlbumArtist:0x007f8e1fc335e8&gt; </code></pre> <p>How can I get this to work?</p> <pre><code>class Album &lt; ActiveRecord::Base has_many :album_artists has_many :artist, through: :album_artists end class AlbumArtist &lt; ActiveRecord::Base belongs_to :album belongs_to :artist # validates_uniqueness_of :name, scope: [:artist_id] end class Artist &lt; ActiveRecord::Base has_many :album_artists has_many :albums, through: :album_artists # validates_uniqueness_of :name, scope: [:artist_id] end </code></pre> <p><strong>Schema</strong></p> <pre><code>create_table "albums", force: :cascade do |t| t.string "name" end create_table "album_artists", force: :cascade do |t| t.integer "album_id" t.integer "artist_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "album_artists", ["album_id"], name: "index_album_artists_on_album_id" add_index "album_artists", ["artist_id"], name: "index_album_artists_on_artist_id" create_table "artists", force: :cascade do |t| t.string "name" end </code></pre>