Using Omnigraffle to visualise Rails model associations

August 2nd, 2006  |  Published in rails  |  1 Comment

This week I’m doing some Rails consulting work for a company that’s already developed and deployed a major application. Getting to know a new codebase takes a little time and every diagram or visualisation helps. To help me understand their ActiveRecord model relationships, I knocked together a quick script to scan the associations between models and output it in the Graphviz DOT format.

A quick Omnigraffle import later, and I get useful diagrams like this fragment from the BBC Programme Catalogue codebase:

Here’s the code, ready for running from the top of any Rails project (ymmv, etc):

#!/usr/bin/env ruby
require "config/environment"
Dir.glob("app/models/*rb") { |f|
require f
puts "digraph x {"
Dir.glob("app/models/*rb") { |f|
classname = $1.camelize
klass = Kernel.const_get classname
if klass.superclass == ActiveRecord::Base
puts classname
klass.reflect_on_all_associations.each { |a|
puts classname + " -> " + + " [label="+a.macro.to_s+"]"
puts "}"


  1. Travelsheep » Blog Archive » graphing models in rails says:

    December 19th, 2008 at 4:12 pm (#)

    […] found a script to generate a graphviz input file at Matt Biddulph’s blog. So first thing I did was to create a new file in my rails root directory, I called it […]