I am just starting a new Rails 3 project using Mongoid ORM for MongoDB. There is just one thing I can not get my head around, and that is how to effectively have a many-to-many relationship. Now there is a good chance that I may be approaching this problem wrong, but as far as I know, there is at least two containers in my project that need a many-to-many relationship. I would prefer to treat both models as "first class" models and allocate each with its own container.
This is the simplest way I can think to structure my many-to-many relationship:
// Javascript pseudo modeling
// -------------------- Apps
{
app: {
_id: "app1",
name: "A",
event_ids: ["event1","event2"]
}
}
{
app: {
_id: "app2",
name: "B",
event_ids: ["event1"]
}
}
// -------------------- Events
{
event: {
_id: "event1",
name: "Event 1",
}
}
{
event: {
_id: "event2",
name: "Event 2",
}
}
As far as I can tell this is the minimum amount of information need to infer a many-to-many relationship. My assumption is that I might have to have a map reduce procedure to determine what apps belong to an event. I would also have to write post commit/save hooks on Event to update App.event_ids if an app is added to or removed from an event model.
Am I on the right track here? If someone has any Mongoid or Mongomapper code examples of a many-to-many relationship working, could you please share.