2013-02-13 62 views
2

我正在尝试使用Mongoid Model Tree Structures with Parent References
父母设置为空Mongoid与父参考为空

这是我的课:

class Category 
    include Mongoid::Document 
    field :name, type: String 
    belongs_to :parent, :class_name => 'Category' 
end 

这就是我如何创建类别:

parent = Category.new(name: "Mobile").save! 
child1 = Category.new(name: "Android", parent: parent).save! 
child2 = Category.new(name: "iOS", parent: parent).save! 

结果:

{ 
    "categories": [ 
     { 
      "_id": "511b84c5cff53e03c6000126", 
      "name": "Mobile", 
      "parent_id": null, 
     }, 
     { 
      "_id": "511b84c5cff53e03c6000128", 
      "name": "Android", 
      "parent_id": null, 
     }, 
     { 
      "_id": "511b84c5cff53e03c6000129", 
      "name": "iOS", 
      "parent_id": null, 
     } 
    ] 
} 

父甚至没有存储在数据库:

{ "name" : "Mobile", "_id" : "511b84c5cff53e03c6000126" } 
{ "name" : "Android", "_id" : "511b84c5cff53e03c6000128" } 
{ "name" : "iOS",  "_id" : "511b84c5cff53e03c6000129" } 

做什么错了?

谢谢!
Roei

+0

看不到你的'has_one'声明 – apneadiving 2013-02-13 12:38:32

+0

@apneadiving我应该在哪里使用'has_one'?谢谢! – Roei 2013-02-13 15:48:21

+0

@Roei我猜你是缺少foreign_key子句试试这个'foreign_key =>:parent_id' ans看看它是否有帮助 – Viren 2013-02-14 05:07:33

回答

0

当我单独保存(而不是与创建同一行)时,它最终奏效了。

之前(不正常工作):

parent = Category.new(name: "Mobile").save! 
child1 = Category.new(name: "Android", parent: parent).save! 
child2 = Category.new(name: "iOS", parent: parent).save! 

后(工作!):

parent = Category.new(name: "Mobile") 
child1 = Category.new(name: "Android", parent: parent) 
child2 = Category.new(name: "iOS", parent: parent) 

parent.save 
child1.save 
child2.save 

结果(如预期):

{ "name" : "Mobile", "_id" : "511b84c5cff53e03c6000126" } 
{ "name" : "Android", "parent_id" : "511b84c5cff53e03c6000126", "_id" : "511b84c5cff53e03c6000128" } 
{ "name" : "iOS", "parent_id" : "511b84c5cff53e03c6000126", "_id" : "511b84c5cff53e03c6000129" } 

非常感谢所有响应者!

+0

如何获取所有父类别。 类别:其中(:parent_id =>无) 不起作用。 – aashish 2014-06-08 10:25:00

1

除了声明belongs_to关联中,你需要声明相反has_many协会,即使是在同一类。

class Category 
    include Mongoid::Document 
    field :name, type: String 

    has_many :children, 
    class_name: 'Category', 
    inverse_of: :parent 
    belongs_to :parent, 
    class_name: 'Category', 
    inverse_of: :children 
end 

您可以通过关联指定父项或子项。

parent = Category.create 
child1 = Category.create 
child2 = Category.create 

parent.children << child1 
parent.children << child2 

然后,孩子们将存储对父母的引用。

+0

我也试过这个,但是结果相同 - null。谢谢! – Roei 2013-02-13 14:26:36

+0

你是通过关联分配父母/孩子吗? – 2013-02-13 21:05:08

+0

@ThomasKlemn我只使用'belongs_to:parent,:class_name =>“Category”'来定义关系。我设法让它工作,张贴我的答案。感谢您的回应! – Roei 2013-02-14 08:42:06