#mongodb #mongomapper
#mongodb #mongomapper
Вопрос:
Учитывая следующий класс, как я мог бы разрешить узлу иметь отношения «многие ко многим» с другими узлами (например, parent_node
и child_nodes
)?
class Node
include MongoMapper::Document
key :text, String
end
Ответ №1:
Могут ли дочерние элементы иметь более одного родителя? Если нет, то many/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
Это то, что вы ищете?