Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 284
agentargo Avatar asked Nov 27 '25 09:11

agentargo


1 Answers

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

like image 108
Matt Avatar answered Nov 29 '25 00:11

Matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!