【问题标题】:many to many relationships with mongoid与 mongoid 的多对多关系
【发布时间】:2014-08-08 00:07:39
【问题描述】:

我想知道如何与 mongoid 建立多对多关系。这是模型的可视化表示,小的是连接表:

!http://i.imgur.com/lJxoRSb.jpg

我已经使用 RoR 像这样(作为示例)设置了我的模型:

class Event
  include Mongoid::Document

  field :name, type: String
  field :place, type: String
  field :when, type: String
  field :price, type: Integer
  field :participants, type: Integer
  field :short_description, type: String

  has_many :users
  #has_many :users, :through => :user_events
end

我需要什么将事件模型与用户模型和兴趣模型加入(如果这可能的话)?我知道 mongoid 不是最好的选择,但我坚持使用它。

提前致谢!

【问题讨论】:

标签: mongodb ruby-on-rails-4 mongoid


【解决方案1】:

尝试以下方法:

embeds_many :user_events

另见http://mongoid.org/en/mongoid/v3/relations.html#embeds_many

不要在 MongoDB 中使用连接表,而是使用嵌入对象/引用的数组。 MongoDB有数组值,好好利用吧!

对于多对多关系,您可以选择将引用放置在第一个集合上,或第二个集合上,或两者上。如果您将引用放在两个集合中,则必须根据应用程序的需要进行自己的更新以保持一致性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    相关资源
    最近更新 更多