如何模型许多家长很多自我指涉的关系? [英] How to model a many self-referential relationship with many parents?

查看:199
本文介绍了如何模型许多家长很多自我指涉的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要模拟出最简单的方法如下:

I want to model out the following in the easiest way:

一个技能有很多相关的技能。

A skill has many dependent skills.

每个技能应该存在于自己的,和技能可能有其他的技能,prerequisite技能。

Each skill should exist on their own, and a skill may have other skills that are prerequisite skills.

例如:

Skill: Front-End Development Has Dependent Skills -> [HTML, CSS, SCSS]
Skill: Web-Design Has Dependent Skills -> [HTML, CSS]
Skill: HTML

我希望能够做到:

I'd like to be able to do:

@front_end_development.dependent_skills ##or a more semantic mapping

我可能会喜欢走了树,但我不认为这样做最好的名字。也许我想通过HTML引用一个网页设计依赖于它。

I'd probably like to walk up the tree but I can't think of the best name to do so. Perhaps I'd like to reference through HTML that Web-Design depends upon it.

是否有意义,使这个自我指涉或者是事实,这是伤害我的脑子code气味和求别的东西是理想的?这一切都归结到这取决于其他技能的技能。

Does it make sense to make this self-referential or is the fact that this is hurting my brain a code smell and beg that something else is ideal? It all comes down to a skill depending on other skills.

难道是更好地使用这种蒙戈模式?

Would it be better to model this using mongo?

推荐答案

而不是通过树遍历(更像是一个有向图实际上)每次需要检索所有依赖关系的技能的时候,你可能只是通过暗示迭代添加依赖性,当一个新的依赖于特定的技能和这些保存到一个名为'依赖'表,技能映射到一个依赖关系,反之亦然。例如(的关系,可以更好地措辞):

Instead of iterating through the tree (more like a directed graph actually) each time you need to retrieve all dependencies for a skill, you might just iterate through the implied dependencies when adding a new dependency to a particular skill and save these to a table called 'Dependency' which maps a skill to a dependency and vice versa. For example (the relations could be better worded):

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

您应该然后就可以做这样的事情:

You should then be able to do things like:

@front_end_development.dependencies
@front_end_development.depending
@front_end_development.add_dependency(@html)

这篇关于如何模型许多家长很多自我指涉的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆