agentargo
agentargo

Reputation: 401

Structuring Complex Relationships in Mongoid

Say I have two seperate models User and Event in a HABTM environment.

Now I want to extend this to include information about the relation. Things like if the user is planning on attending the event.

In standard ActiveRecord this would be done with a has_many :through relationship, but from what I have been reading it is a bad idea to try and create this kind of relationship in mongoid. What is a good way to approach this problem? (staying with mongo)

Here's an example of what I would expect for this type of functionality:

class User
  field :name
  has_many :user_events
  has_many :events, :through => :user_events
end

class Event
  field :title 
  has_many :user_events
  has_many :users, :through => :user_events
end

class UserEvent
  field :attending?, :type => Boolean
  belongs_to :users
  belongs_to :events
end

Upvotes: 3

Views: 1483

Answers (1)

Matt
Matt

Reputation: 17649

class User
  include Mongoid::Document

  field :name
  embeds_many :user_events
end

class UserEvent
  include Mongoid::Document

  belongs_to :event 
  embedded_in :user

  field :attending?, :type => Boolean
end

class Event
  include Mongoid::Document
  field :title
end

In order to find all events where the user is attending:

user = User.where(:name => 'Joe').first
user.user_events.where(:attending? => true)

For a complete example see this gist

Upvotes: 3

Related Questions