Ruby on rails 具有父引用的Mongoid为空
我正在尝试使用Mongoid,Ruby on rails 具有父引用的Mongoid为空,ruby-on-rails,ruby-on-rails-3,mongodb,mongoid,parent-child,Ruby On Rails,Ruby On Rails 3,Mongodb,Mongoid,Parent Child,我正在尝试使用Mongoid, 但是父项被设置为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: "
但是父项被设置为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" }
我做错了什么
谢谢Roei除了声明一个
属于
关联之外,您还需要声明另一个具有多个
关联,即使它属于同一类
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
parent=Category.create
child1=Category.create
child2=Category.create
parent.children当我单独保存时(与创建不在同一行),它最终起作用了
之前(工作不正常):
工作之后
结果(如预期的那样):
非常感谢所有响应者 看不到您的有一个declaration@apneadiving我应该在哪里使用has_one?谢谢@Roei我想你缺少外键子句试试这个foreign\u key=>:parent\u id
ans看看是否有help@Viren我设法让它工作(不需要外键),张贴了我的答案。谢谢你的回复!您是否通过关联来分配父/子关系?@ThomasKlemn我仅使用'belowns\u to:parent,:class\u name=>“Category”来定义关系。我设法使它工作,张贴我的答案。谢谢你的回复!如何获取所有父类别。类别。其中(:parent_id=>nil)不起作用。
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" }