我正在嘗試使用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
看不到你的'has_one'聲明 – apneadiving 2013-02-13 12:38:32
@apneadiving我應該在哪裏使用'has_one'?謝謝! – Roei 2013-02-13 15:48:21
@Roei我猜你是缺少foreign_key子句試試這個'foreign_key =>:parent_id' ans看看它是否有幫助 – Viren 2013-02-14 05:07:33