在 Mongoid 中构建复杂的关系

发布于 2024-11-01 18:16:27 字数 559 浏览 0 评论 0原文

假设我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无声静候 2024-11-08 18:16:27
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

为了查找用户参加的所有活动:

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

有关完整的示例,请参阅此 gist

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文