Mongoid自引用加入

时间:2010-12-05 21:29:21

标签: ruby-on-rails ruby-on-rails-3 mongoid self-reference

我目前正在开发一款小型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

使用rails控制台,如果我设置了任一属性,它将永远不会反映在连接的另一侧,并且有时在保存和重新加载后会丢失。我肯定答案是瞪着我的脸 - 但经过几个小时的凝视,我仍然看不到它。

2 个答案:

答案 0 :(得分: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。

答案 1 :(得分: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