我试图在 Rails (3.2.12) 和 Mongoid (3.1.2) 中实现一个非常简单的“多重关系”。我得到了三个模型:
class User
include Mongoid::Document
field :name
has_many :collections
end
class Collection
include Mongoid::Document
field :name
belongs_to :user
has_many :things
end
class Thing
include Mongoid::Document
field :name
belongs_to :collection
end
所以基本上有一个用户有收藏,也有收藏有“东西”。嗯......第一个问题:这甚至可能吗?如果不是:为什么不呢?;-)
我现在可以创建用户(从 Rails 控制台或通过 Web),我可以创建属于用户的集合。但是当我现在尝试创建一个“事物”时......它只是没有被创建:
2.0.0-p0 :014 > u = User.first
=> #<User _id: 514b2b32e05658e1f1000005, name: "test">
2.0.0-p0 :015 > c = Collection.create!(name: "somename", user: u)
=> #<Collection _id: 514b30f0e05658ca67000001, name: "somename", user_id: "514b2b32e05658e1f1000005">
2.0.0-p0 :016 > t = Thing.create!(name: "a thing", collection: c)
=> #<Thing _id: 514b3120e05658ca67000002, name: "a thing", collection_id: "514b30f0e05658ca67000001">
2.0.0-p0 :017 > Thing.first
=> nil
“集合”创建得很好:
2.0.0-p0 :018 > Collection.first
=> #<Collection _id: 514b2b65e05658e1f1000006, name: "test", user_id: "514b2b32e05658e1f1000005">