问题
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 that are prerequisite skills.
For example:
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
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.
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?
回答1:
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)
来源:https://stackoverflow.com/questions/11532187/how-to-model-a-many-self-referential-relationship-with-many-parents