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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.