2011-09-21 65 views
2

嗨,大家好我有一類像下面的履帶模型:mongoid自我與自我的關係?

class Link 
    include Mongoid::Document 
    include Mongoid::Timestamps 
    field :url, type: String 
    field :links, type: String 
    index :url 
    has_many :pages 
end 

裏的某個鏈接悔改一個URL,他們有很多的入站/出站連接,我想有它的工作,所以:

a_link.links # => gives a list of outbound link objects. 

你會怎麼做與mongoid?

回答

9

您可以在關係的每一側使用has_and_belongs_to_many設置多對多關聯。

class Link 
    include Mongoid::Document 
    has_and_belongs_to_many :links, :class_name => 'Link', :inverse_of => :inbound_links 
    has_and_belongs_to_many :inbound_links, :class_name => 'Link', :inverse_of => :links 
end 

作爲該協會是從在這種情況下,你需要給mongoid與CLASS_NAME的幫助不大相同的類和inverse_of,因爲它不能從關聯名推斷此。

+0

它的工作方式,謝謝! – c2h2

+0

沒問題,很高興它的工作 – Steve

2

有點清潔歸檔此使用多對多協會

class Link 
    include Mongoid::Document 
    has_and_belongs_to_many :links, class_name: 'Link', inverse_of: :links 
end 
+0

這似乎並沒有在另一端添加鏈接到文檔的參考。 (請參閱此處的示例對話:https://github.com/openfarmcc/OpenFarm/pull/924#pullrequestreview-33231415) – Simon