views:

181

answers:

1

We are creating a rails application for an already existing database. We need to map some database tables together.

Suppose we have three tables: event, event_groups and event_to_groups.
There are some events, there are some groups, and each event can be assigned to one or more groups.

How do I model this relation in rails?

eg:

Existing tables:

event
    ID      name
    --------------------
    3       dinner
    4       sport
    5       anniversary
    6       birthday

event_groups
    ID      name
    --------------------
    1       work
    2       friends
    3       family

event_to_groups
    event_id    event_groups
    --------------------
    3           2
    3           3
    4           1
    4           2
    4           3
    5           3
    6           2
class Events < ActiveRecord::Base
  set_table_name 'events'
end
class Groups < ActiveRecord::Base
  set_table_name 'groups'
end
class EventToGroups < ActiveRecord::Base
  set_table_name 'event_to_groups'
end

How can I retrieve group names belonging to an event from the event model? Thanks.

+1  A: 

A few things - first of all, the ActiveRecord model should be singular, not plural. Also, I assume you meant that the table for the Group model is 'event_groups', and not 'groups'?

Try this:

class Event < ActiveRecord::Base
  set_table_name 'events'
  has_many :event_to_groups
  has_many :groups, :through => :event_to_groups
end

class Group < ActiveRecord::Base
  set_table_name 'event_groups'
  has_many :event_to_groups
  has_many :events, :through => :event_to_groups
end

class EventToGroup < ActiveRecord::Base
  set_table_name 'event_to_groups'
  belongs_to :event
  belongs_to :group, :foreign_key => 'event_groups'
end

I'd also choose a more descriptive model name than "EventToGroup" (maybe "Attendee" or something), but that's up to you.

That should do it - then you can do something like:

@event = Event.find(5)
@groups = event.groups

Edit: Ack, those relationships should be has_many, not just many. I've been using MongoMapper too much.

PreciousBodilyFluids