每次您需要检索技能的所有依赖项时,不必遍历树(实际上更像是有向图),您可能只是在向特定技能添加新依赖项时遍历隐含的依赖项并将它们保存到名为“依赖关系”将技能映射到依赖关系,反之亦然。例如(关系可以更好地措辞):
class Skill
has_many :dependers, class_name: 'Dependency', foreign_key: :dependee_id
has_many :dependees, class_name: 'Dependency', foreign_key: :depender_id
has_many :dependencies, through: :dependees
has_many :depending, through: :dependers
def add_dependency(skill)
recurse_dependencies(skill)
end
def recurse_dependencies(skill)
# perform this check to avoid circular and duplicate dependencies
if !depender_ids.include?(skill.id) && !dependee_ids.include?(skill.id)
dependee_ids << skill.id
end
skill.dependencies.each do |dependency|
recurse_dependencies(dependency)
end
end
end
class Dependency
belongs_to :dependee
belongs_to :depender
end
然后,您应该能够执行以下操作:
@front_end_development.dependencies
@front_end_development.depending
@front_end_development.add_dependency(@html)