gpt4 book ai didi

ruby-on-rails - 具有父引用的 Mongoid 为空

转载 作者:可可西里 更新时间:2023-11-01 10:44:26 26 4
gpt4 key购买 nike

我正在尝试做 Model Tree Structures with Parent References使用 Mongoid,
但是 parent 设置为 null

这是我的课:

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" }

哪里做错了?

谢谢!
荣荣

最佳答案

除了声明 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 或 child 。

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

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

然后子级将存储对父级的引用。

关于ruby-on-rails - 具有父引用的 Mongoid 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14853629/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com