How to model a many self-referential relationship with many parents?

前端 未结 1 743
礼貌的吻别
礼貌的吻别 2021-01-25 18:32

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

A skill has many dependent skills.

Each skill should exist on their own, and a skill may have other skills

相关标签:
1条回答
  • 2021-01-25 19:01

    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)
    
    0 讨论(0)
提交回复
热议问题