views:

221

answers:

2

Hello all,

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

A: 

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.

Matt Briggs
Hey Matt, thanks for your input. It's valuable in that it confirms 1) I am not crazy to suspect there is genuinely no good way yet to do many2many assoc. --- I just, just dug up a slide by Kyle Banker here http://www.slideshare.net/kbanker/mongodb-the-way-and-its-power on the 52nd slide, he demo how to do a m-2-m product-category assoc by storing category objectIds in product.in pseudo language if one is to find all products in a category: Product.find category_id = 123. but to find all categories in a product, you have to start from category class:Category.find(id in product.category.ids.
Nik
@Nik: Honestly, I am probably only about a month and a half passed where you now, and only had an answer so quick because it wasn't that long ago I was looking for the same info ;-) I would highly recommend watching this http://vimeo.com/9864311, helped me a lot.
Matt Briggs
@Matt, thanks for the link and your experience. -- at least makes me feel better that I'm not alone in this, to say the least.
Nik