开发者

Model that references many of itself?

Given the following class, how would I allow a node to have a many to many relationship with other nodes (such as parent_node and child_nodes)?

class Node
  include MongoMapper::Document

  key :text开发者_StackOverflow, String
end


Can children have more than one parent? If not, many/belongs_to should work fine:

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

If nodes can have multiple parents...

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

Is that what you're looking for?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜