【问题标题】:Mongoid persistance problems with a 1 to many association具有 1 对多关联的 Mongoid 持久性问题
【发布时间】:2011-06-27 04:14:12
【问题描述】:

我有以下型号:

班比尔 . . .一些领域。 . . belongs_to :sponsor, :class_name => "立法者" 结尾 阶级立法者 ..一些领域。 . . has_many :票据 结尾

我得到了这种奇怪的行为,但我确信这很简单:

加载开发环境(Rails 3.0.7) b = Bill.first l = 立法者.first l.票据 真 (我可以查看 l.bills,但 l.bills.all.to_a.count 为 0) l.govtrack_id => 400001 ruby-1.9.2-p180 :007 > Legislator.where(govtrack_id: 400001).first.bills => []

所以我可以创建关联并查看它。保存成功,但是当我检索对象时,关联消失了。 . .没有错误。我很困惑,我错过了什么?

【问题讨论】:

    标签: ruby-on-rails mongodb mongoid


    【解决方案1】:

    您的Legislator 模型上缺少inverse_of。我进行了快速测试(以确保没有 Mongoid 问题)。我的模型是这样的:

    class Bill
      include Mongoid::Document
      include Mongoid::Timestamps
      field :name
      belongs_to :sponsor, :class_name => "Legislator"
    end
    
    class Legislator
      include Mongoid::Document
      include Mongoid::Timestamps
    
      field :govtrack_id
      has_many :bills, :inverse_of => :sponsor
    end
    

    以及来自测试的控制台输出:

    ruby-1.9.2-p180 > Bill.create(:name => "A new bill")
      => #<Bill _id: 4e0822636a4f1d11c1000001, _type: nil, created_at: 2011-06-27 06:25:39 UTC, updated_at: 2011-06-27 06:25:39 UTC, name: "A new bill", sponsor_id: nil>
    ruby-1.9.2-p180 > Legislator.create(:govtrack_id => "400123")
      => #<Legislator _id: 4e0822786a4f1d11c1000002, _type: nil, created_at: 2011-06-27 06:26:00 UTC, updated_at: 2011-06-27 06:26:00 UTC, govtrack_id: "400123">
    ruby-1.9.2-p180 > l = Legislator.first
    ruby-1.9.2-p180 > l.bills << Bill.first
      => [#<Bill _id: 4e0822636a4f1d11c1000001, _type: nil, created_at: 2011-06-27 06:25:39 UTC, updated_at: 2011-06-27 06:26:08 UTC, name: "A new bill", sponsor_id: BSON::ObjectId('4e0822786a4f1d11c1000002')>] 
    ruby-1.9.2-p180 > l.save!
      => true
    ruby-1.9.2-p180 > Bill.first.sponsor.govtrack_id
      => "400123"
    ruby-1.9.2-p180 > Legislator.first.bills
     => [#<Bill _id: 4e0822636a4f1d11c1000001, _type: nil, created_at: 2011-06-27 06:25:39 UTC, updated_at: 2011-06-27 06:26:08 UTC, name: "A new bill", sponsor_id: BSON::ObjectId('4e0822786a4f1d11c1000002')>]
    

    【讨论】:

    • 优秀。正是我需要的。我通读了我能找到的文档,你有关于 :inverse_of 的文档链接吗?
    • Mongoid 文档看起来很棒,但有些东西确实很难找到! :) 在this page 的底部有一个简短的参考。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多