2010-12-05 24 views
1

私は現在、働いている秘密のサンタを追跡するのに役立つ小さなRails 3アプリを開発中です。私はすべて終わったばかりで、この最後の問題を解決しようとすると完全に困惑しました。モンゴイド自己参照結合

私は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)。

これは自己参照1対1の関係を実装する最も簡単な方法だと思います。私は、コンソールでこれをテストし、それが私の仕事:

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

2

ジャスト日まで滞在し、あなたはActiveRecordのに非常に近くに滞在することができ2+ mongoidで:

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。