0

I'm wondering on how to do a many to many relationship with mongoid. Here is a visual representation of the models, with the small ones being join tables:

!https://i.stack.imgur.com/H3dA5.jpg

I have set up my model like this (as an example) using RoR:

class Event
  include Mongoid::Document

  field :name, type: String
  field :place, type: String
  field :when, type: String
  field :price, type: Integer
  field :participants, type: Integer
  field :short_description, type: String

  has_many :users
  #has_many :users, :through => :user_events
end

what would i need to join the event model with user model with interest model (if this is even possible)? I know mongoid isn't the best option for this but i'm stuck with using it.

Thanks in advance!

meowmixplzdeliver
  • 197
  • 1
  • 3
  • 9
  • Have you seen this? http://stackoverflow.com/questions/4839881/how-to-organise-a-many-to-many-relationship-in-mongodb – Ace Caserya Aug 08 '14 at 00:16
  • I think you are trying for has_many :through, which is not used in mongoid. You don't have joins here. – Bijendra Aug 12 '14 at 09:33

1 Answers1

0

Try the following:

embeds_many :user_events

See also http://mongoid.org/en/mongoid/v3/relations.html#embeds_many

Do not use join tables in MongoDB, use arrays of embedded objects/references instead. MongoDB has array values, take advantage of them!

With a many-to-many relationship, you have a choice on placing the references on the first collection, or the second collection, or on both. If you put references in both collections, you have to do your own updates for consistency as needed by your application.

Gary Murakami
  • 3,392
  • 1
  • 16
  • 20