Rails has_many :through association

喜你入骨 提交于 2019-12-04 10:01:39

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

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 =)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!