Generating an Entity Relationship Diagram for your Rails application

Posted . Visible to the public. Repeats.

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

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
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2022-02-18 08:55)