ruby on rails-Mongoid持久性问题与1对多关联



我有以下模型:

班级账单…一些字段。belongs_to:赞助商,:class_name=>"立法者"终止阶级立法者…一些字段。has_many:账单终止

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

加载开发环境(Rails 3.0.7)b=账单第一l=立法者第一l.bills<lt;bl.save=>真(我可以查看l.bills,但l.bills.all.to_a.count为0)l.govtrack_id=>400001ruby-1.9.2-p180:007>立法者。其中(govtrack_id:40001).first.bills=>[]

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

您的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')>]

最新更新