title: Simulating has_many :through with Mongoid
body: <p>I'm trying to create an event platform using MongoDB as the db. I want a many-to-many relationship between <code>Events</code> and <code>Users</code>. The thing is, I want there to be properties in the relationship (e.g., <code>Users</code> can either be confirmed or unconfirmed for a specific <code>Event</code>). I realize this would be ideally suited for an RDBMS, but I'm using MongoDB for reasons that I'm taking advantage elsewhere and I would prefer to continue using it. </p>
  
  <p>What I would like is for each <code>Event</code> to embed many <code>Guests</code>, which belong to <code>Users</code>. That way, I can see which users are attending an event quickly and with only one query. However, I would also like to see which <code>Events</code> a <code>User</code> is attending quickly, so I would like each <code>User</code> to have an array of <code>Event</code> ids. </p>
  
  <p>Here is a code summary.</p>
  
  <pre class="lang-rb prettyprint-override"><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 =&gt; :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 =&gt; u, :confirmed =&gt; true)
  </code></pre>
  
  <p>With the ideal use pattern, <code>e</code> has a <code>Guest</code> with a reference to <code>u</code> and <code>u</code> has a reference to <code>e</code>.</p>
  
  <p>I know the <code>has_many :through</code> line won't work. Any suggestions as to how to get similar functionality? I was thinking of using an <code>after_create</code> callback in <code>Guest</code> to add a reference to the <code>Event</code> in <code>User</code>, but that seems pretty hacky. </p>
  
  <p>Maybe I've gone down the wrong path. Suggestions? Thanks.</p>