degenPenguin
degenPenguin

Reputation: 725

Many-to-Many User and Event associations

I am having trouble wrapping my mind around this. My goal is to create the simplest following relationships:

  1. Event belongs_to Poster (User)
  2. Event has_many Hosts (Users)
  3. Event has_many Reservations (Users)
  4. Event has_many Upvoters (Users)
  5. Event has_many Attendees (Users)
  6. Event has_many Guests (Users)


  1. User has_many Posts (Events)
  2. User has_many Hosted (Events)
  3. User has_many Reservations (Events)
  4. User has_many Upvotes (Events)
  5. User has_many Attended (Events)

So far, my approach has been with 4 models:

class Event < ApplicationRecord
  belongs_to :poster, class_name: "User"
  has_many :hosts, class_name: "User"
  has_many :votes, foreign_key: 'voted_id', dependent: :destroy
  has_many :upvoters, through: :votes, source: :voter

class User < ApplicationRecord
  has_many :posts, class: "Event"

  has_many :votes, foreign_key: 'voter_id', dependent: :destroy
  has_many :upvotes, through: :votes, source: :voted

class Vote < ApplicationRecord
  belongs_to :voter, class_name: "User"
  belongs_to :voted, class_name: "Event"

class Membership < ApplicationRecord
  belongs_to :user
  belongs_to :event

Is there a way I can utilize the Membership class for each of the following relationships (except voting)?

Upvotes: 0

Views: 80

Answers (1)

Pablo
Pablo

Reputation: 3005

You can try something like this:

class Membership < ApplicationRecord
  belongs_to :user
  belongs_to :event
  enum type: [ :host, :reservation, :attendance ]
end

class Event < ApplicationRecord
  belongs_to :poster, class_name: "User"

  has_many :host_memberships, -> { host }, class_name: "Membership"
  has_many :reservation_memberships, -> { reservation }, class_name: "Membership"
  has_many :attendance_memberships, -> { attendance }, class_name: "Membership"

  has_many :hosts, through: :host_memberships, source: "User"
  has_many :reservations, through: :reservation_memberships, source: "User"
  has_many :attendees, through: :attendance_memberships, source: "User"
end

class User < ApplicationRecord
  has_many :posts, class_name: "Event"

  has_many :host_memberships, -> { host }, class_name: "Membership"
  has_many :reservation_memberships, -> { reservation }, class_name: "Membership"
  has_many :attendance_memberships, -> { attendance }, class_name: "Membership"

  has_many :hosted, through: :host_memberships, source: "Event"
  has_many :reservations, through: :reservation_memberships, source: "Event"
  has_many :attended, through: :attendance_memberships, source: "Event"
end

Upvotes: 0

Related Questions