Reputation: 1706
I have User
who can make an Event
. These are the organizers.
Other User
s can go to these Event
s 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
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
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