2
votes

I just began using Mongoid last week. I am running into this association problem which I am unsure if my approach is correct. So i thought I would ask for some opinion

I have a User model and a Project model class User include Mongoid::Document field :email end class Project include Mongoid::Document field :name end

Actually the user model is created by Devise, an authentication gem, so I guess it cannot be embedded in Project.

So if I wanted the old many to many associations where a user can have many projects and a project can have many users. how should I set this up?

My approach is this: class User include Mongoid::Document field :email references_many :projects referenced_in :project, :inverse_of => :users end class Project include Mongoid::Document field :name references_many :users referenced_in :user, :inverse_of => :projects end

Is this the correct way with respect to MongoDB architecture to do such a many-to-many association?

Thank you

2

2 Answers

5
votes

The Mongoid documentation explains how to do this at http://mongoid.org/en/mongoid/docs/relations.html#has_and_belongs_to_many . Scroll down to the heading Relational Associations. In the code example that's shown, there's a many-to-many relationship between the Person and Preference models.

1
votes

document databases are actually pretty terrible when it comes to many-to-many, since that is pretty much the essence of relational data. mongo shines when the data is hierarchical rather then relational.

What I would do (assuming there will be more to users then just their email), is store the users in a seperate collection, and store arrays of user ids in your project documents. If it is just emails, I would store them inside the project documents, and just accept that it will be more expensive then it probably should be for users to change their email.