Last active
February 27, 2021 23:13
-
-
Save ideasasylum/8ec41b90131307edb9a36143b5fa977c to your computer and use it in GitHub Desktop.
Check if an ActiveRecord model can be destroyed, and in what order the association should be deleted
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Rails.application.eager_load! | |
class ActiveRecordDependancyGraph | |
include TSort | |
attr_reader :graph | |
def initialize root_model | |
@graph = {} | |
@model = root_model | |
fetch_children @model | |
end | |
def fetch_children model | |
return if model.nil? | |
return if graph[model.name] | |
child_models = model.reflect_on_all_associations(:has_many).collect do |ar| | |
ar.klass | |
rescue NameError => e | |
end | |
graph[model.name] = child_models.compact.collect &:name | |
child_models.each do |child| | |
fetch_children child | |
end | |
end | |
def tsort_each_child(model_name, &block) | |
graph[model_name].each(&block) | |
end | |
def tsort_each_node(&block) | |
graph.each_key(&block) | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ActiveRecordDependancyGraph.new(Site).tsort | |
#=> TSort::Cyclic: topological sort failed: ["MailerPreference", "Course", "DripSequence", "Student", "MembershipSubscription", "MembershipPost", "MembershipPlan", "Visitor", "CourseCategory"] | |
ActiveRecordDependancyGraph.new(Section).tsort | |
#=> ["Video", "Download", "SectionRestriction", "StudentContentBlock", "Like", "Comment", "ContentBlock", "Section"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment