rubymongodblogicmongomapperdatabase

MongoMapper: how do I create a model like this


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.


Solution

  • 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_users or assigned_tasks, and a one-to-many relationship with which you get to either the creator of a task, or the created_tasks for a given user. If you chose these names for the relationships, it will be clear which is which.

    class Task
      include MongoMapper::Document
      key :title, String , :required => true
    
      key :user_ids , Array
      has_many :users, :in => user_ids     # , :as => :assigned_users
    
      key :creator_id , ObjectId
      belongs_to: user, :as => :creator
    
    end
    
    class User
      include MongoMapper::Document
      key: name, String, :required => true
    
      has_many :tasks           # , :as => :assigned_tasks
    
      has_many :tasks, :as => :created_tasks
    end
    

    See:

    http://mongomapper.com/documentation/plugins/associations.html