开发者

Mongoid persistance problems with a 1 to many association

I have the following model:

class Bill
 . . . some fields . . .
belongs_to :sponsor, :class_name => "Legislator"
end
class Legislator
  .. .some fields . . .
  has_many :bills
end

I get this strange behavior, but I am sure this is something simple:

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
 => [] 

So I can create the assoc开发者_JAVA技巧iation and view it. The save is successful, but when I retrieve the object, the association is gone . . . no errors. I'm confused, what am I missing?


You're missing inverse_of on your Legislator model. I ran a quick test (to make sure there wasn't a Mongoid issue). My models were thus:

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

And console output from the test:

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')>]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜