开发者

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
  h开发者_运维百科as_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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜