具有父引用的Mongoid为null

时间:2013-02-13 12:30:27

标签: ruby-on-rails ruby-on-rails-3 mongodb mongoid parent-child

我正在尝试使用Mongoid,Model Tree Structures with Parent References父级设置为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,
        }
    ]
}

父级甚至没有存储在DB中:

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

出错了什么?

谢谢!
Roei

2 个答案:

答案 0 :(得分: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

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

答案 1 :(得分:0)

最后,当我单独进行保存时(而不是与创建相同的行),它有效。

之前(不正常):

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

之后(工作!):<​​/ p>

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

非常感谢所有响应者!