Question

I'm trying to create a rails app where user can create events and invite participants to it and need your help! I've been going in circle, trying few things but doesn't seem right at all and this is now driving me crazy!! I'm using rails 4.

How would you setup the active model?

User
has_many :events through :meeting   //for the participants?
has_many :events     // for the organizer?

Event
belongs to :user
has_many :participants, class_name: "User"


Participant
belongs to :user
has_many :events through :meeting

Meeting
has_many :participants
has_many :events

Does that make any sense? Do I need the Participant Model or am I just over-engineering it? I guess I'm a bit confused with organizer is a user and participants are also users and meeting needs both organizer and participants so not so clear how to make this work...

Also read I could build the meeting relationship only when participant has been added. Would that be the way to go? Thank you!

Was it helpful?

Solution 2

First of all you don't need a participant model. This is the structure I'll use if there is some extra information I want to store in the meeting model. If not you can directly use has_and_belongs_to_many.

User
has_many :meetings
has_many :attending_events, through: :meetings, source: "Event"   //for the participants
has_many :events     // for the event organiser

Event
belongs to :user // The organiser
has_many :meetings
has_many :participants, through: :meetings, source: "User"  

Meeting
belongs_to :participant, class_name: "User"
belongs_to :attending_event, class_name: "Event" // Use attending_event_id as foreign_key

OTHER TIPS

No, you don't need the Participant model:

User
has_many :meetings
has_many :events, through: :meetings

Event
has_many :meetings
has_many :participants, through: :meetings, class_name: "User"

Meeting
belongs_to :user
belongs_to :event

From an instance of User you can do:

user.events # => List of Events

And from an instance of Event you can do:

event.participants # => List of Users

The has_many :through explanation in Ruby Guides is similar to what you want to do, check it out.

you don't want to do:

has_many :events
has_many :events #doesn't matter that it's a through table

I've done this in the past and did...

User
  has_many :invites, dependent: :destroy
  has_many :invited_events, through: :invites, source: :event

Event
  has_many :invites, dependent: :destroy
  has_many :invitees, through: :invites, source: :user

Invite
  belongs_to :event
  belongs_to :user

Then in the invite join table, have a boolean column for creator to know if that user created the event. You can also add a column to show whether the user accepted the invite or not (to show participation).

Clean and simple has_many through... not complex =)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top