Ruby on rails 如何实现mongoid多对多关联?

Ruby on rails 如何实现mongoid多对多关联?,ruby-on-rails,many-to-many,mongoid,Ruby On Rails,Many To Many,Mongoid,我想把一个社交网络移植到Mongoid。朋友之间的连接表非常大。Mongoid有没有现成的方法来处理这个连接表?我已经看到了一些模型中的滚动您自己的解决方案,但没有什么看起来有效。有办法解决这个问题吗?或者这是我不应该使用Mongoid的情况吗?您不需要使用MongoDB进行多对多关系和连接表。每个用户都将其整个好友图存储在实际的用户对象上,以及其他所有内容,如首选项、图片(GridF)等。如果您需要做需要关系代数的特殊工作,只需使用RDBMS,否则MongoDB将很好地工作。可以进行高级查询,

我想把一个社交网络移植到Mongoid。朋友之间的连接表非常大。Mongoid有没有现成的方法来处理这个连接表?我已经看到了一些模型中的滚动您自己的解决方案,但没有什么看起来有效。有办法解决这个问题吗?或者这是我不应该使用Mongoid的情况吗?

您不需要使用MongoDB进行多对多关系和连接表。每个用户都将其整个好友图存储在实际的用户对象上,以及其他所有内容,如首选项、图片(GridF)等。如果您需要做需要关系代数的特殊工作,只需使用RDBMS,否则MongoDB将很好地工作。可以进行高级查询,但必须使用mapreduce。

对于缩放应用程序,应避免多对多。例如,Twitter所做的是在用户对象中以逗号分隔格式(字符串)存储追随者ID。 使用MongoDB甚至更好,因为它支持阵列


请记住,最能描述NoSQL的是术语NoJoin;-)

您可以使用关系关联创建多对多(多态)关联,并将关系存储为数组

class Person
  include Mongoid::Document
  field :name
  references_many :preferences, :stored_as => :array, :inverse_of => :people
end

class Preference
  include Mongoid::Document
  field :name
  references_many :people, :stored_as => :array, :inverse_of => :preferences
end

ps1 = Person.create(:name => 'John Doe')
pf1 = Preference.create(:name => 'Preference A')
pf2 = Preference.create(:name => 'Preference B')

ps1.preferences << pf1
ps1.preferences << pf2
ps1.save

pf1.people.each {|ps| puts ps.name }
ps1.preferences.each {|pf| puts pf.name }
班级人员
include Mongoid::Document
字段:名称
引用\u many:preferences、:storage\u as=>:array、:reverse\u of=>:people
结束
阶级偏好
include Mongoid::Document
字段:名称
引用\u many:people,:storage\u as=>:array,:reverse\u of=>:preferences
结束
ps1=Person.create(:name=>johndoe)
pf1=首选项。创建(:name=>“首选项A”)
pf2=首选项。创建(:name=>“首选项B”)

ps1.preferences此方法已被弃用。您现在可以在许多类似的地方使用references_和referenced_:

class Person
  include Mongoid::Document
  field :name
  references_and referenced_in_many :preferences
end

class Preference
  include Mongoid::Document
  field :name
  references_and referenced_in_many :people
end

我们只需要将用户的好友ID存储为用户对象上的数组,对吗?mongoid有办法解决这个问题吗?或者我需要自己编写它们吗?因此,如果所有的东西都嵌入了MongoDB中,并且MongoDB中没有多对多关系这样的东西,我会假设更新冗余的非规范化数据一定很困难“在大量创建/更新具有许多关系的对象时,许多存储为数组的引用的速度可能非常慢。一个更传统的RDBMS将很容易胜过Mongo”:是的,这样的选择可能会很慢。如果这是一个问题,您也可以创建一个“加入”集合,如果您愿意的话。只需使用您的应用程序进行加入。请注意,
:storage_as
已在2.0.0中消失,请参阅。