简体   繁体   English

Rails:建模此has_and_belongs_to_many关联的最佳方法是什么

[英]Rails: what is the best way to model this has_and_belongs_to_many association

Let's say I have two models Event and Person . 假设我有两个模型EventPerson

Many people attend an event and a person can attend many events too. 很多人参加一个活动,一个人也可以参加很多活动。

class Event < ActiveRecord::Base
  has_and_belongs_to_many :people
end

class Person < ActiveRecord::Base
  has_and_belongs_to_many :events
end

create_table "events_people", :id => false, :force => true do |t|
  t.integer "event_id"
  t.integer "person_id"
end

The problem is that an event is presented by one or many speakers . 问题是一个或多个speakers主持了一个活动。 So for a particular event , we should have people who attend that event and one or many speakers who are, of course, people too. 因此,对于一个特定的event ,我们应该有people谁参加该事件和一个或多个speakers谁是当然的,人太多。

How do I do that ? 我怎么做 ? Thank you. 谢谢。

Try this: 尝试这个:

class Event < ActiveRecord::Base
  has_and_belongs_to_many :people
  has_and_belongs_to_many :speakers, :class_name => "Person"
end

And you would have an events_speakers join table that would match event_id and person_id (which would point to ids in your people table). 你将有一个events_speakers连接表,将匹配event_idperson_id (这将指向中的ID people表)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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