A Diagram For Your Rails Records

Sometimes, when it’s getting late, after a few beers and when you have more than a couple of Active Records in your project, things can get a bit blurry. What is linked to what? Did I make that a belong_to or a has_many? Clearly, the bigger picture can elude you.

Fortunately, I just discovered (thanks to Matt Biddulph) some way to generate a quick and easy diagram showing how your active records play with each other. But don’t start thinking I needed this because I had a beer. I did not. Or did I? Anyway, it’s fortunately pretty simple.

  1. First you’ll need graphviz. If you’re running the right O/S it’s as straightforward as ‘apt-get install graphviz’. The two of you running Fedora can replace apt-get by yum, I’m guessing it would work just as well. For Windows and Mac users, it’s just a download.
  2. Save the Ruby script reproduced below in a ‘graph.rb’ file located at the root of your Rails project.
  3. Run ‘ruby graph.rb | dot -Tpng -ograph.png’. It won’t work with the wrong O/S (understand Windows). You’ll have to save the output of the script in a file and then run the second part of the command on that file. Also if you’re dorky enough to have some ‘puts’ in your ActiveRecord you’ll have to save the output in a file as well and clean that up.
  4. Open graph.png.

Here is the promised script (slight improvements from the original).

#!/usr/bin/env ruby

require "config/environment"

Dir.glob("app/models/*rb") { |f| require f }puts "digraph x {"

Dir.glob("app/models/*rb") do |f|

classname = f.match(//([a-z_]+).rb/)[1].camelize

klass = Kernel.const_get classname

if ActiveRecord::Base >= klass

puts classname

klass.reflect_on_all_associations.each do |a|

label = (a.macro.to_s =~ /many/) ? "*" : "1"

puts "#{classname} -> #{a.name.to_s.camelize.singularize} [label=\"#{label}\"]"




puts "}"

And here is an example of the result:


2 comments so far

  1. tnlessone on

    I can only advise :

  2. COOL on

    But this isnt what i looked up

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: