我目前正在开发一个小的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控制台,如果我设置了任何一个属性,它都不会反映在连接的另一边,有时会在保存和重新加载后全部丢失。我确信答案就在我面前--但经过几个小时的凝视,我仍然看不到它。
发布于 2010-12-06 06:22:00
这个问题有点棘手。拥有一个自引用的多对多关系实际上更容易(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发布于 2012-03-15 19:37:44
为了保持最新,您可以使用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
endHTH。
https://stackoverflow.com/questions/4361321
复制相似问题