title: How to create a custom where.missing query for complex has_many through association
body: <p>I have a complex has_many through assocation which looks like the below:</p>
  <pre><code>class Artist &lt; ApplicationRecord
    has_many :artist_masters, -&gt;(artist) {
      unscope(:where).where(artist_id: artist.id)
                     .or(where(composer_id: artist.id))
                     .or(where(performer_id: artist.id))
                     .or(where(conductor_id: artist.id))
    }
    has_many :masters, through: :artist_masters
  end
  
  class Master &lt; ApplicationRecord
    has_many :artist_masters, dependent: :destroy
    has_many :artists, through: :artist_masters
    has_many :composers, class_name: 'Artist', through: :artist_masters
    has_many :performers, class_name: 'Artist', through: :artist_masters
    has_many :conductors, class_name: 'Artist', through: :artist_masters
  end
  
  class ArtistMaster &lt; ApplicationRecord
    belongs_to :master
    belongs_to :artist, optional: true
    belongs_to :composer, class_name: 'Artist', optional: true
    belongs_to :performer, class_name: 'Artist', optional: true
    belongs_to :conductor, class_name: 'Artist', optional: true
  end
  </code></pre>
  <p>Thanks to <a href="https://stackoverflow.com/questions/24642005/rails-association-with-multiple-foreign-keys/41978449#41978449">this post</a> for the help with that.</p>
  <p>However this stops <code>Artist.where.missing(:masters)</code> or <code>Artist.where.missing(:artist_masters)</code> from working.</p>
  <p>I need to recreate this so that it returns all Artists who's id is not present in any artist_id, performer_id, composer_id or conductor_id.</p>
  <p>If i run <code>Artist.where.missing(:artist_masters).first</code> I get an error:</p>
  <pre><code>ArgumentError: The association scope 'artist_masters' is instance dependent (the scope block takes an argument). Preloading instance dependent scopes is not supported.
  </code></pre>
  <p>If i run <code>Artist.where.missing(:masters).first</code> I get an error:</p>
  <pre><code>NoMethodError: undefined method 'id' for nil:NilClass
  
      unscope(:where).where(artist_id: artist.id)
                                             ^^^
  </code></pre>