1

私は現在、職場で秘密のサンタを追跡するのに役立つ小さなRails 3アプリに取り組んでいます。この最後の問題を解決しようとして、私はほとんど終わっていて、完全に困惑しています。

Participant誰が誰のためにギフトを購入する必要があるかを表すには、自己結合が必要なモンゴイド ドキュメントがあります。私が何をしても、これを機能させることができないようです。私のコードは次のとおりです。

# 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

Rails コンソールを使用して、いずれかのプロパティを設定すると、結合の反対側に反映されず、保存して再読み込みした後にすべてが失われることがあります。その答えが私の顔を睨みつけていることは確かですが、何時間もじっと見つめた後でも、まだそれを見ることができません。

4

2 に答える 2

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。

于 2012-03-15T11:37:44.360 に答える
1

それは少しトリッキーです。自己参照型の多対多の関係を持つ方が実際には簡単です (この質問に対する私の回答を参照してください)。

これは、自己参照型の 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
于 2010-12-05T22:22:00.013 に答える