开发者

Mongoid self-referencial join

I am currently working on a small Rails 3 app to help track secret-santas at work. I am all but done and completely stumped trying to sort out this last problem.

I have a Participant mongoid document, which requires a self-join to represent who has to buy gifts for whom. No matter what I do, I don't seem to be able to get this to work. My code is as follows:

# app/models/participant.rb
class Participant
include Mongoid::Document
incl开发者_C百科ude 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

Using the rails console, if I set either property it is never reflected on the other side of the join, and sometimes lost all together after saving and reloading. I'm certain that the answer is glaring me in the face - but after hours of staring, I still can't see it.


Just to stay up to date, with mongoid 2+ you can stay very close to 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.


That one is a little tricky. Having a self-referential many-to-many relationship is actually easier (see my answer to this question).

I think this is the simplest way of implementing a self-referential one-to-one relationship. I tested this out in the console and it worked for me:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜