Rails has_many: through association

I am trying to create a rails application where a user can create events and invite participants to them, and you need your help! I'm going in a circle, tried a few things, but it doesn't seem right, and now it drives me crazy! I use rails 4.

How to set up an 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 sense? Do I need a participant model or am I just overestimating it? I assume that I am a little confused with the organizer - this is the user, and the participants are also users and meet the needs of both the organizer and the participants, so it is not so clear how to make this work ...

Also read that I could only build a meeting relationship when a member was added. Will it be the way? Thank!

+4
3

, . , , - , . , 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
+1

, Participant:

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

User :

user.events # => List of Events

Event :

event.participants # => List of Users

has_many: Ruby Guides , , .

+3

:

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

I did 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 invitation table, attach a boolean column for creatorto see if this user created this event. You can also add a column to show whether the user accepted the invitation or not (to show participation).

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

0
source

Source: https://habr.com/ru/post/1534587/


All Articles