Modeling has_many: through Mongoid

I am trying to create an event platform using MongoDB as db. I want a many-to-many relationship between Events and Users . The fact is that I want the relationship to have properties (for example, Users can be confirmed or not confirmed for a specific Event ). I understand that this is ideal for RDBMSs, but I use MongoDB for reasons that I use elsewhere, and I would prefer to continue to use it.

I would like each Event insert many Guests owned by Users . Thus, I can see which users are attending the event quickly and with only one request. However, I would also like to see which Events a User attends quickly, so I would like each User have an array of Event ids.

Here is a summary of the code.

 # user of the application class User has_many :events end # event that users can choose to attend class Event embeds_many :guests has_many :users, :through => :guests # Won't work end # guests for an event class Guest field :confirmed?, type: Boolean embedded_in :event belongs_to :user end # Ideal use pattern u = User.create e = Event.create e.guests.create(:user => u, :confirmed => true) 

With an ideal usage pattern, e has a Guest with a link to u , and u has a link to e .

I know that the has_many :through line will not work. Any suggestions on how to get similar functionality? I was thinking of using the after_create in Guest to add a link to the Event in User , but that seems pretty hacky.

Perhaps I went the wrong way. Suggestions? Thanks.

+4
source share
2 answers

You can simply store the event IDs in an array on the user.

You need to control the array when for some reason the event changes or the user is removed from the event. But this is a compromise.

Custom events can then be found with a single db call.

See observers to manage the association.

+3
source

I ended up using callbacks in the models to execute that I wanted. Here is how it looks.

Edit: I just saw nodrog. Yes, the use of observers would probably be more accurate, I did not know about them. Thanks!

 # user of the application class User has_and_belongs_to_many :events, inverse_of: nil, dependent: :nullify end # event that users can choose to attend class Event embeds_many :guests index 'guests.user_id', unique: true before_destroy :cleanup_guest_references def cleanup_guest_references self.guests.each do |guest| guest.destroy end end end # guests for an event class Guest field :confirmed?, type: Boolean embedded_in :event, :inverse_of => :guests belongs_to :user after_create :add_event_for_user before_destroy :remove_event_for_user private def add_event_for_user self.user.events.push(self.event) end def remove_event_for_user self.user.events.delete self.event self.user.save end end 
+2
source