2012-01-13 123 views
0

假设我有两个模型EventPersonRails:模拟这个has_and_belongs_to_many协会的最佳方式是什么

许多人参加一个活动,一个人也可以参加很多活动。

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 

的问题是,一个事件是由一个或多个呈现speakers。因此,对于某个特定的event,我们应该有people参加该活动,以及一个或多个speakers,他们当然也是人。

我该怎么做?谢谢。

回答

1

试试这个:

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

而且你将有一个events_speakers连接表,将匹配event_idperson_id(这将指向中的ID people表)。

+0

我还没有尝试过自己的代码,但是从我如何理解activerecord关联的导轨指南来看,它对我来说在'events_speaker'表中是'speaker_id',而不是'person_id'是有意义的。这是因为HABTM协会寻找演讲者。 – rocketscientist 2012-01-15 06:43:00

相关问题