开发者

Mongoid weirdness

开发者 https://www.devze.com 2023-04-02 01:56 出处:网络
I\'m sure it\'s just some very basic MongoDB concept that I fail to understand, but this drives me insane.

I'm sure it's just some very basic MongoDB concept that I fail to understand, but this drives me insane.

I have 2 really simple Mongoid models in my Rails 3.1 application

class Box
  include Mongoid::Doc开发者_如何学Pythonument
  field :name, :type => String
  embeds_many :things
end

class Thing
  include Mongoid::Document
  field :name, :type => String
  embedded_in :box
end

I create 2 boxes

Box.create :name => "Big"
=> #<Box _id: 4e5e5c051c3a2b2efc00009d, _type: nil, name: "Big">

Box.create :name => "Small"
=> #<Box _id: 4e5e5c251c3a2b2efc00009e, _type: nil, name: "Small">

The first strange thing I noticed is this

Box.all.count
=> 2

Box.all.collect &:name
=> ["Big", "Small"]

Box.all.first
=> #<Box _id: 4e5e5c051c3a2b2efc00009d, _type: nil, name: "Big">

Box.all.last
=> #<Box _id: 4e5e5c051c3a2b2efc00009d, _type: nil, name: "Big">

first and last are the same? What the...?

The next strange thing happens when I add things to a box

my_box = Box.find "4e5e5c051c3a2b2efc00009d"
=> #<Box _id: 4e5e5c051c3a2b2efc00009d, _type: nil, name: "Big">

my_box.things.create :name => "Stuff"
=> #<Thing _id: 4e5e5ee11c3a2b2efc00009f, _type: nil, name: "Stuff">

my_box.things.all.count
=> 1

# ... add a bunch of other things

my_box.things.all.count
=> 5

my_box.things.create :name => "Stuff"
=> #<Thing _id: 4e5e5eeb1c3a2b2efc0000a4, _type: nil, name: "Stuff">

my_box.things.all.count
=> 2

Whoa! Has my database just lost a bunch of stuff?

What is happening here? Is this expected behavior?


You may try following

class Box
  include Mongoid::Document
  field :name, :type => String
  references_many :things
end

class Thing
  include Mongoid::Document
  field :name, :type => String
  referenced_in :box
end


Thanks for your suggestions everyone.

This apparently was an ugly side effect from using Mongoid with Rails 3.1. Works like a charm with Rails 3.0.

For the records: do not try to use Mongoid 2.2.0 with Rails 3.1.

0

精彩评论

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

关注公众号