1

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

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

# 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

那个有点棘手。拥有自我引用的多对多关系实际上更容易(请参阅我对这个问题的回答)。

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

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 回答