2010-12-05 53 views
1

我目前正在研究一個小型的Rails 3應用程序,以幫助跟蹤工作中的祕密聖誕老人。我幾乎完成了,並試圖理清這最後一​​個問題。Mongoid self-referencial join

我有一個Participant mongoid文檔,它需要自我加入來表示誰必須爲他們購買禮物。無論我做什麼,我似乎都無法得到這個工作。我的代碼如下:

# app/models/participant.rb 
class Participant 
include Mongoid::Document 
include Mongoid::Timestamps 

field :first_name, :type => String 
field :last_name, :type => String 
field :email, :type => String 
# --snip-- 

referenced_in :secret_santa, :class_name => "Participant", :inverse_of => :receiver 
references_one :receiver, :class_name => "Participant", :inverse_of => :secret_santa 

使用軌道控制檯,如果我設置這兩個屬性這是從來沒有反映在聯接的另一邊,有時保存和重裝後丟失了一起。我敢肯定,答案是讓我眼前一亮 - 但經過幾個小時的盯着,我仍然看不到它。

回答

1

這是一個有點棘手。擁有自我參照的多對多關係實際上更容易(see my answer to this question)。

我認爲這是實現自引用一對一關係的最簡單方法。我在控制檯中測試了這一點,它的工作對我來說:

class Participant 
    include Mongoid::Document 
    referenced_in :secret_santa, 
       :class_name => 'Participant' 

    # define our own methods instead of using references_one 
    def receiver 
    self.class.where(:secret_santa_id => self.id).first 
    end 

    def receiver=(some_participant) 
    some_participant.update_attributes(:secret_santa_id => self.id) 
    end  
end 

al = Participant.create 
ed = Participant.create 
gus = Participant.create 

al.secret_santa = ed 
al.save 
ed.receiver == al   # => true 

al.receiver = gus 
al.save 
gus.secret_santa == al # => true 
+0

謝謝!那就是訣竅。 – theTRON 2010-12-05 23:28:03

2

只是爲了保持最新,與mongoid 2+你可以保持非常接近的ActiveRecord:

class Participant 
    include Mongoid::Document 
    has_one :secret_santa, :class_name => 'Participant', :inverse_of => :receiver 
    belongs_to :receiver, :class_name => 'Participant', :inverse_of => :secret_santa 
end 

HTH。