简体   繁体   中英

Rails join tables

I have the following models

User
Meeting
Participant

Particpant < User
Meeting belongs_to :user
Meeting has_many :participants

I have the following join table

create_table 'meetings_participants', :id => false do |t|
  t.column :meeting_id, :integer
  t.column :participant_id   , :integer
end

I want to add t.column :confirmed_at , :datetime so that I know when and if a user has confirmed that they are attending a meeting but I dont know the best way to do it.

How can I set confirmed_at? Since this is

Your plan is fine: just add :confirmed_at :datetime as a field in the meetings_participants join table.

You may want to reserve a null :confirmed_at to mean that they were invited to the meeting but never confirmed. And didn't attend? Can someone attend a meeting that they didn't confirm their attendance at?

I usually include the :id in join tables even though it is not really needed. There are a lot of rails assumptions about all tables having ids.

added

You should add a unique index on [:meeting_id, :participant_id] to your join table.

added

You can certainly have join tables represented by ActiveRecord models in Rails apps. Include an id field in the table to keep ActiveRecord happy. Example:

class MeetingsParticipant < ActiveRecord::Base
  # join table. Table name: meetings_participants

  belongs_to :meeting
  belongs_to :participant

  # field confirmed_at is nil for invited participants who have
  #                    not yet confirmed attendance

end

To do this, I think it is best to have a good look at the models you set up and do abit of refactoring. What you want is a user related to a meeting . I think the best way to get this relational model, is to introduce another model: participant this is a user related to a meeting. Your models would look like:

User
  has_many :participants
  has_many :meetings, through: :participants

Participant
  belongs_to :user
  belongs_to :meeting

Meeting
  has_many :participants
  has_many :users, through: :participants

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM