Mongoid自我参考集合has_many不起作用

时间:2013-07-29 05:37:36

标签: ruby-on-rails mongodb mongoid

无法理解为什么这不起作用

class User
  include Mongoid::Document

class Student < User
  include Mongoid::Document
  ....
  has_one :parent , class_name: "Parent", inverse_of: :children

class Parent < User
  include Mongoid::Document
  ....
  has_many :children, class_name: "Student", inverse_of: :parent

当我尝试通过

设置父/子关系时
jane = Student.create!(name: "Jane")
janesParent = Parent.new(name: "Jenny")
janesParent.children.push(jane)
janesParent.save!

我收到此错误

  When adding a(n) Student to Parent#children, Mongoid could not determine the    
  inverse foreign key to set. The attempted key was 'parent_id'.

我做错了什么?

P.S我不想嵌入这些想要存储id的适用类型。

2 个答案:

答案 0 :(得分:3)

如果是1-N关系,请将Student模型关系更改为

belongs_to :parent, class_name: "Parent", inverse_of: :children

答案 1 :(得分:2)

您是否尝试过has_and_belongs_to_many关系?