many to many table with an extra column in Rails

微笑、不失礼 提交于 2019-12-03 16:49:23

User and Event have many-to-many relationship, you can not set up this association with just 2 model, you must have the join model, or join table.

In your case, you added attribute confirmed, so you will need a join model, named Confirmation (as other people recommended). Your define associations will be like this:

class User
  has_many :events, through: :confirmations
  has_many :confirmations
end

class Event
  has_many :users, through: :confirmations
  has_many :confirmations
end

class Confirmation
  belongs_to :user
  belongs_to :event
end

Instead of use for the User model, with the relation

has_and_belongs_to_many :events

and modify the join table Events_Users (it's a bit dirty)

is better to use a model Confirmation with two belongs_to relations:

belongs_to :user
belongs_to :event

I hope this can help you, Alessandro

Since you have the extra field on the join table you'll want a join model. Check this out:

class User
  has_many :invitations
  has_many :invited_events,   -> {where(confirmed: false)}, class_name: 'Event', through: :invitations
  has_many :confirmed_events, -> {where(confirmed: true)},  class_name: 'Event', through: :invitations
end

class Event
  has_many :invitations
  has_many :invited_users,   -> {where(confirmed: false)}, class_name: 'User', through: :invitations
  has_many :confirmed_users, -> {where(confirmed: true)},  class_name: 'User', through: :invitations
end

class Invitation
  belongs_to :user
  belongs_to :event
end

With this, user.confirmed_events will provide the user's events only where the confirmed flag is set to true in the join table.

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