I have a complex has_many through assocation which looks like the below:
class Artist < ApplicationRecord
has_many :artist_masters, ->(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 < 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 < 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
Thanks to this post for the help with that.
However this stops Artist.where.missing(:masters)
or Artist.where.missing(:artist_masters)
from working.
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.
If i run Artist.where.missing(:artist_masters).first
I get an error:
ArgumentError: The association scope 'artist_masters' is instance dependent (the scope block takes an argument). Preloading instance dependent scopes is not supported.
If i run Artist.where.missing(:masters).first
I get an error:
NoMethodError: undefined method 'id' for nil:NilClass
unscope(:where).where(artist_id: artist.id)
^^^