← Back to Upcase

Join Table Association Uniqueness Validation/Restrictions


(Alex Bush) #1

Hello fellow developers :slight_smile:

I have a “architecture” question regarding join models and associations:

I have a User, Festival, and Artists models. Festival has_many artists.
Every User can add artists from a festival to “my lineup” specifically for particular festival(meaning that if the user adds one artist from festival_1 to his/her lineup and another one from festiva_2 those two artists will be in different lineups)
Easy enough I created a UserLineup model(prbly should’ve named it just Lineup but we already use UserLineup in the iOS app). And set every user to have multiple user_lineups. Then every UserLineup has_many artists and belongs_to festival and user effectively making it a join model with some metadata.
There are also two join models: Performance(between Festivals and Artists) and Lineupization(between UserLineup and Artists). I guess I just post the code instead of describing it:

class User
  has_many :user_lineups
  has_many :lineup_artists, :through => :user_lineups, :class_name => 'Artist', :source => :artists    
end

class Festival
   has_many :performances, :dependent => :destroy
   has_many :artists, :through => :performances, :uniq => true
end

# Join between festivals and artists
class Performance
   belongs_to :artist
   belongs_to :festival
end

class Artist
   has_many :performances, :dependent => :destroy
   has_many :festivals, :through => :performances
end


class UserLineup
   belongs_to :festival
   belongs_to :user
   
   has_many :lineupizations, :dependent => :destroy
   has_many :artists, :through => :lineupizations
end

# Join between UserLineups and Artists
class Lineupization < ActiveRecord::Base
  belongs_to :artist
  belongs_to :user_lineup
end

The questions I have:

  1. Is this a good setup with multiple join tables? I mean I feel like I go nuts with them use it too much but at the same time I kinda feel it’s the right approach
  2. Lineupization - good or bad name? :slight_smile:
    3) And the most important question - how should I go about validating Artists that are added to a lineup? meaning I want to restrict Artists that are added to a UserLineup only to those that also belong to Festival that this UserLineup was created with. My use case is simple, I use it for JSON APIs to serve an iOS app and I already tested(speced) out this behavior in my JSON controllers specs but I still feel that models should handle it somehow.