Search code examples
ruby-on-railsassociationsmodel-associations

What is the correct Rails association for an events website?


I need some advice on my rails event app, I can't figure out the correct association that I need in my models so I have broken it down for some guidance.

Speaker & Event Model

  • An event has many speakers
  • A speaker can belong to many events

Session, Speaker & Event Model

  • An event has many sessions
  • A session can belong to many events
  • A session has one speaker
  • A speaker can belong to many sessions

More info

The idea is that the event organiser can add speakers to an event and list them on the event show page and then closer to the event date, the event organiser builds the agenda using sessions. The agenda view has all the session information i.e. time, title as well as the speaker information that is associated to that session.


Solution

  • Since you are planning to add speakers to an event first, and then later allow a moderator to organize them into sessions, I'd say you are very close to a working solution. Here's what I would recommend:

    class Event
      has_many :events_speakers
      has_many :speakers, through: :events_speakers
      has_many :sessions
    end
    
    class Speaker
      has_many :events_speakers
      has_many :events, through: :events_speakers
      has_many :sessions_speakers
      has_many :sessions, through: :sessions_speakers
    end
    
    class Session
      # fields include: title, time
      belongs_to :event
      has_many :sessions_speakers
      has_many :speakers, through: :sessions_speakers
    end
    

    A few notes:

    • I chose to allow a session to have many speakers to handle cases of panels or discussions
    • A speaker has and belongs to many events to allow for easy adding of past speakers to new events or to show a speaker bio page with a list of events they have participated in.

    If you know you'll never need either of those features, then you could simplify by removing the HABTM relationships.

    One main change from your summary above is that I believe a Session should belong to only one Event. A session is an instance of a person/people speaking at a certain time, at a specific event, which is why it has a time attribute. If you need these sessions to repeat in the future, it makes sense to copy them to new session instances