首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Mongoid自引用连接

Mongoid自引用连接
EN

Stack Overflow用户
提问于 2010-12-06 05:29:21
回答 2查看 1.6K关注 0票数 1

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

我有一个Participant mongoid文档,它需要一个自连接来表示谁必须为谁购买礼物。无论我做什么,我似乎都不能让它工作。我的代码如下:

代码语言:javascript
运行
复制
# 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控制台,如果我设置了任何一个属性,它都不会反映在连接的另一边,有时会在保存和重新加载后全部丢失。我确信答案就在我面前--但经过几个小时的凝视,我仍然看不到它。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-12-06 06:22:00

这个问题有点棘手。拥有一个自引用的多对多关系实际上更容易(see my answer to this question)。

我认为这是实现自我引用一对一关系的最简单方式。我在控制台中测试了这一点,它对我来说很有效:

代码语言:javascript
运行
复制
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
票数 1
EN

Stack Overflow用户

发布于 2012-03-15 19:37:44

为了保持最新,您可以使用mongoid 2+与ActiveRecord保持非常密切的关系:

代码语言:javascript
运行
复制
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。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4361321

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档