引用许多自身的模型?

时间:2011-10-02 16:54:40

标签: mongodb mongomapper

鉴于以下类,我如何允许节点与其他节点(例如parent_nodechild_nodes)建立多对多的关系?

class Node
  include MongoMapper::Document

  key :text, String
end

1 个答案:

答案 0 :(得分:5)

孩子可以有多个父母吗?如果没有,很多/ belongs_to应该可以正常工作:

class Node
  include MongoMapper::Document

  key :text, String
  key :parent_node_id, ObjectId

  belongs_to :parent_node, :class_name => 'Node'
  many :child_nodes, :foreign_key => :parent_node_id, :class_name => 'Node'
end

如果节点可以有多个父母......

class Node
  include MongoMapper::Document

  key :text, String
  key :parent_node_ids, Array, :typecast => 'ObjectId'

  many :parent_nodes, :in => :parent_node_ids, :class_name => 'Node'

  # inverse of many :in is still forthcoming in MM
  def child_nodes
    Node.where(:parent_node_ids => self.id)
  end
end

# ... or store an array of child_node_ids instead ...

class Node
  include MongoMapper::Document

  key :text, String
  key :child_node_ids, Array, :typecast => 'ObjectId'

  many :child_nodes, :in => :child_node_ids, :class_name => 'Node'

  # inverse of many :in is still forthcoming in MM
  def parent_nodes
    Node.where(:child_node_ids => self.id)
  end
end

这就是你要找的东西吗?