a person
a person

Reputation: 1706

how to do a relation which has a has_many and belongs_to

I have User who can make an Event. These are the organizers.

Other Users can go to these Events as attendees.

How should I do the following relation?

User:

has_many :events, foreign_key: organizer_id
belongs_to :event

Event:

belongs_to :user #how to do the organizer and attendees distinction?

Upvotes: 0

Views: 33

Answers (2)

Sajad Rastegar
Sajad Rastegar

Reputation: 3154

I recommend to create a event_attends table and put user_id and event_id columns there and user_id and event_attend_id in events table. Then you could create the associations like this:

class User < ActiveRecord::Base
  has_many :event_attends
  has_many :events
end

class Event < ActiveRecord::Base
  belongs_to :user
  has_many :event_attends
end

class EventAttend < ActiveRecord::Base
  belongs_to :user
  belongs_to :event
end

Upvotes: 1

Steve Madsen
Steve Madsen

Reputation: 13791

You need two different relationships on each model with different names, but the same class. Also, you have a many-to-many relationship between attendees and events.

User

has_many :organized_events, class_name: "Event"
has_and_belongs_to_many :attended_events, class_name: "Event"

Event:

belongs_to :organizer, class_name: "User"
has_and_belongs_to_many :attendees, class_name: "User"

Upvotes: 0

Related Questions