我有以下型号:
class Bill . . . some fields . . . belongs_to :sponsor, :class_name => "Legislator" end class Legislator .. .some fields . . . has_many :bills end
我得到了这种奇怪的行为,但我确信这很简单:
Loading development environment (Rails 3.0.7) b = Bill.first l = Legislator.first l.bills << b l.save => true (I can view l.bills, but l.bills.all.to_a.count is 0) l.govtrack_id => 400001 ruby-1.9.2-p180 :007 > Legislator.where(govtrack_id: 400001).first.bills => []
所以我可以创建关联并查看它。保存成功,但是当我检索对象时,关联就消失了。 。 。没有错误。我很困惑,我错过了什么?
答案 0 :(得分:2)
您的inverse_of
型号上遗漏了Legislator
。我跑了一个快速测试(以确保没有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')>]