在 Mongoid 中构建复杂的关系
假设我在 HABTM 环境中有两个独立的用户模型和事件模型。
现在我想扩展它以包含有关关系的信息。例如用户是否计划参加活动等。
在标准 ActiveRecord 中,这可以通过 has_many :through 关系来完成,但从我所读到的内容来看,尝试在 mongoid 中创建这种关系是一个坏主意。解决这个问题的好方法是什么? (继续使用 mongo)
以下是我对此类功能的期望示例:
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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了查找用户参加的所有活动:
有关完整的示例,请参阅此 gist
In order to find all events where the user is attending:
For a complete example see this gist