Laura
Laura

Reputation: 4369

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.

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. So for a particular event, we should have people who attend that event and one or many speakers who are, of course, people too.

How do I do that ? Thank you.

Upvotes: 0

Views: 154

Answers (1)

rocketscientist
rocketscientist

Reputation: 2488

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).

Upvotes: 1

Related Questions