【问题标题】:Mongoid self-referencial joinMongoid 自引用连接
【发布时间】:2010-12-05 21:29:20
【问题描述】:

我目前正在开发一个小型 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 控制台,如果我设置任何一个属性,它永远不会反映在连接的另一侧,有时会在保存和重新加载后一起丢失。我敢肯定,答案让我眼前一亮——但经过数小时的凝视,我仍然看不到它。

【问题讨论】:

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


    【解决方案1】:

    只是为了保持最新状态,使用 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。

    【讨论】:

      【解决方案2】:

      那个有点棘手。拥有自引用的多对多关系实际上更容易 (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-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多