Read more

Generating an Entity Relationship Diagram for your Rails application

Arne Hartherz
February 18, 2022Software engineer at makandra GmbH

This card explains how to generate an entity relationship diagram for your Rails application.
We also show how to limit your ERD to a subset of models, e.g. models inside a namespace.

Generating a full ERD

Option A: RubyMine

  1. Right-click anywhere in your project tree
  2. In the context menu, find the "Diagrams" menu item at/near the bottom
  3. Inside, choose "Show diagram" → "Rails Model Dependency Diagram"
  4. A new tab will open with the diagram inside. You can modify it there, and export it as an image.

Option B: Use rails-erd

  1. Install rails-erd Show archive.org snapshot following the steps in their installation instructions.
  2. Run bundle exec rake erd
  3. Open erd.pdf

Generating an ERD for only some models of a Rails app

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

This is not directly possible with RubyMine. While you can manually remove boxes in the generated diagram, this is cumbersome on large projects, and can't be automated.

You can use rails-erd instead.

As an example, here is a Rake task where we render only Models inside the DataMigration module.

namespace :data_migration do

  task erd: :environment do
    Rails.application.eager_load!

    require 'rails_erd/domain'
    require 'rails_erd/diagram/graphviz'

    model_names = RailsERD::Domain
      .generate(warn: false)
      .entities
      .map(&:model)
      .map(&:name)
      .grep(/^DataMigration::/)

    filename = RailsERD::Diagram::Graphviz.create(
      only: model_names,
      title: 'DataMigration ERD',
      
      # You may add further options here. Example:
      attributes: ['foreign_keys', 'primary_keys'],
      filename: 'data_migration_erd',
      indirect: true,
      orientation: 'vertical',
      warn: false,
    )

    puts "Generated #{filename}"
  end

end
$ rake data_migration:erd 
Generated data_migration_erd.pdf

For more configuration options, see the rails-erd customizing guide Show archive.org snapshot .

Arne Hartherz
February 18, 2022Software engineer at makandra GmbH
Posted by Arne Hartherz to makandra dev (2022-02-18 09:55)