Ruby on rails Mongoid自指联接

Ruby on rails Mongoid自指联接,ruby-on-rails,ruby-on-rails-3,mongoid,self-reference,Ruby On Rails,Ruby On Rails 3,Mongoid,Self Reference,我目前正在开发一个小的Rails 3应用程序,帮助跟踪工作中的秘密圣诞老人。为了解决最后一个问题,我几乎完蛋了,完全被难倒了 我有一个Participantmongoid文档,它需要一个self-join来表示谁必须为谁买礼物。无论我做什么,我似乎都无法让它发挥作用。我的代码如下: # app/models/participant.rb class Participant include Mongoid::Document include Mongoid::Timestamps field :

我目前正在开发一个小的Rails 3应用程序,帮助跟踪工作中的秘密圣诞老人。为了解决最后一个问题,我几乎完蛋了,完全被难倒了

我有一个
Participant
mongoid文档,它需要一个self-join来表示谁必须为谁买礼物。无论我做什么,我似乎都无法让它发挥作用。我的代码如下:

# 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控制台,如果我设置了其中一个属性,它将永远不会反映在连接的另一侧,有时在保存和重新加载后会一起丢失。我确信答案就在我眼前——但经过几个小时的凝视,我还是看不见它。

这个问题有点棘手。拥有自引用的多对多关系实际上更容易()

我认为这是实现自我参照一对一关系的最简单方法。我在控制台中对此进行了测试,它对我起了作用:

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

为了保持最新,使用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