ruby on rails - Validate object based on the owner its parent -


i have has_many through association setup between artist , album models. add album has_many tracks. tracks have has_many through association between artists (i.e. featured artist) feature model serves join table.

i want prevent album artist(s) being featured artist on track. instance:

album = album.find_by(name: "justified") track = album.track.first artist = artist.find_by(name: "justin timberlake")  track.featured_artists << artist   # ^^ should raise error since justin timberlake album's artist 

model setup

class album < activerecord::base   has_many :album_artists   has_many :artists, through: :album_artists end  class track < activerecord::base   belongs_to :album    has_many :features   has_many :featured_artists, through: :features, class_name: "artist", foreign_key: "artist_id" end  class albumartist < activerecord::base   belongs_to :album   belongs_to :artist    validates_uniqueness_of :artist_id, scope: :album_id end  class feature < activerecord::base   belongs_to :track   belongs_to :featured_artist, class_name: "artist", foreign_key: "artist_id" end  class artist < activerecord::base   has_many :album_artists   has_many :albums, through: :album_artists    has_many :features   has_many :tracks, through: :features end 

is there way accomplish using 1 of out-of-the-box validation methods? if not how go in creating custom validator without writing ridiculously long lookup chain album's owner, assuming validator in feature model?

you can test intersection (&) of 2 artists array empty.

class track < activerecord::base   belongs_to :album    has_many :features   has_many :featured_artists, through: :features, class_name: "artist", foreign_key: "artist_id"    validate :featured_artists_cannot_include_album_artists    def featured_artists_cannot_include_album_artists     if (album.artists & featured_artists).present?       errors.add(:featured_artists, "can't include album artists")     end   end end 

Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -