[英]Storing trees in the database
我有一個Rails應用程序,其中我的資源之一稱為“組織”,組織可以有任意數量的子組織。 對此,在數據庫中,我對每個組織條目都有一個父ID。
現在,我的組織模型中有一個方法可以像這樣來構建所有組織樹:
def Organization.build_org_trees_wrapper
parent_nodes = []
parent_orgs = Organization.where(:parent_id => nil)
parent_orgs.each do |org|
parent_node = MyNode.new(org.id, org.name)
parent_node.children_nodes = self.build_org_tree(parent_node)
parent_nodes << parent_node
end
return parent_nodes
end
def Organization.build_org_tree(org_node)
ret = []
org_id = org_node.id
children = Organization.where(:parent_id => org_id)
if !children.empty?
children.each do |child|
child_node = MyNode.new(child.id, child.name)
ret << child_node
child_node.parent_node = org_node
child_node.root_id = root_id
child_node.children_nodes.concat(build_org_tree(child_node))
end
else
return []
end
return ret
end
在控制台中對此進行測試后,它可以完成我想要的操作。 到現在為止還挺好。 但是,現在要實際使用我創建的東西,我想將它放在某個地方,以便至少有用。 這可能意味着兩件事:
好的:
通過調用after_initialize()將其放入實例變量。 我嘗試了此操作,但由於總是返回nil,因此無法使其正常工作:
class Organization < ActiveRecord::Base
after_initialize :set_tree
@trees = nil
def set_tree
@trees = self.build_org_trees_wrapper
end
真棒
將此小狗以某種方式存儲在會話變量,高速緩存或鍵值存儲中,以便我始終可以訪問它。 如果可能的話,我也很樂意提供一些建議。
我在這里也有點不知所措,因此歡迎對我的方法提出任何批評。
編輯(忘記我的節點類):
class MyNode
attr_accessor :id, :name, :parent_node, :children_nodes, :root_id
@id = 0
@name = ""
@parent_node = nil
@children_nodes = []
@root_id = 0
def initialize(id, name)
@id = id
@name = name
@children_nodes = []
end
def to_s
return "Name: #{self.name} Org-id: #{self.id}"
end
end
嘗試自己實現所有這些邏輯(以便學習)固然不錯,但我更喜歡使用gem
作為此類功能。 有多個選項。 我個人將ancestory gem
( https://github.com/stefankroes/ancestry )用於此類應用程序。 我似乎認為這枚寶石不適用於Rails 4,但它確實適用於此,如此處所述: 祖先寶石適用於Rails 4嗎? 。
您可以在以下SO問題/答案中找到更多選項: 樹菜單的acts_as_tree vs祖先gem
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.