首页 > 解决方案 > 如何处理具有 has_many 和 belongs_to 的关系

问题描述

User有谁能做一个Event。这些是组织者。

其他人可以作为参加者User去这些人。Event

我应该如何做以下关系?

用户:

has_many :events, foreign_key: organizer_id
belongs_to :event

事件:

belongs_to :user #how to do the organizer and attendees distinction?

标签: ruby-on-railsactiverecord

解决方案


我建议创建一个表并在表event_attends中放置user_idevent_id列。然后你可以像这样创建关联:user_idevent_attend_idevents

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

推荐阅读