Suppose we have two models, Task and User.
So a user can have many tasks and tasks should be able to have many users too. But, a task should also have a unique creator who is also a user.
Exemple:
A task in this context is like this:
Task ID, Task Creator, Users who should do the task
User_1 creates a task and he is then the creator.
User_1 specifies User_2 and User_3 as users who should do the task. So these two last users are not creators of task.
How do I create this models so that if I have a task object, I can find it’s creator and users who should complete it. And how do I do, if I have a user, to find all tasks he created and all tasks he should complete.
You’ll need a many-to-many relationship between the Tasks and Users, and you need an additional one-to-many relationship between Users and Tasks, pointing to the creator (User).
Something along these lines: (I usually use Mongoid, so double-check the syntax for the relations in the MongoMapper API – link below.. you might to manually specify :foreign_key and :class)
The idea is that you have two relationships between the models, one which models the many-to-many relationship
with which you get either to the
assigned_usersorassigned_tasks, and a one-to-many relationship with which you get to either thecreatorof a task, or thecreated_tasksfor a given user. If you chose these names for the relationships, it will be clear which is which.See:
http://mongomapper.com/documentation/plugins/associations.html