문제

I'm trying to achieve a really simple "multiple relationship" in Rails (3.2.12) with Mongoid (3.1.2). I got three models:

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

So basically there is a user who has collections and there are collections which have "Things". Well ... first question: Is this even possible? And if not: Why not? ;-)

I can create users now (from a rails console or via web), and I can create collections belonging to users. But when I try to create a "Thing" now ... well it just doesn't get created:

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 

The "Collection" gets created just fine:

2.0.0-p0 :018 > Collection.first
 => #<Collection _id: 514b2b65e05658e1f1000006, name: "test", user_id: "514b2b32e05658e1f1000005"> 
도움이 되었습니까?

해결책

Change the Collection class name to something else, say to 'Stockpile'. MongoDB uses 'collection' as part of it's terminology, so it may not play well with your models.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top