2013-02-13 66 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