Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Check if an ActiveRecord model can be destroyed, and in what order the association should be deleted
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
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