Baby step - 思考と実験の足跡

日常のちょっとした、気になって試したこと集です。

rails-erdでER図を自動生成した

背景

テーブル設計時のコミュニケーションを取りやすくするため、ER図を作ろうとしました。 ER図を作るツールはいくつかありますが、GUIタイプのは肌に合わず、plantumlはコードで書けるものの都度更新が必要だなあ、と。

自動で作ってくれるものはないかな〜と探したら rails-erd というgemがあったので、導入してみました。

Rails ERDとは?

  • gemの1つです
  • ActiveRecordModelの定義を元にER図を生成します
  • オプションに依って、スキーマ更新時に自動生成できます

導入

ruby: 2.7.1
rails: 6.0.3.2

まずはgemを追加します。

group :development do
  gem "rails-erd"
end

graphvizの追加も必要です。 apt-get install -y graphviz などで追加しましょう。

使い方

rails erd を実行するだけです。

ER図が生成されます。簡単ですね!

設定

プロジェクト直下のディレクトリに.erdconfigを作成しましょう。 yaml形式でオプションの指定ができます。

cf. Rails ERD – Customisation options

  • attributesのprimary_keys
  • filename
  • title

あたりを指定すると良さそうです。

また、filename: doc/erdのようにすることで、doc直下に生成させることもできます。

注意点

バージョン

READMEにはRails3.0-5.0用と書かれています。

Rails ERD was created specifically for Rails and works on versions 3.0-5.0. It uses Active Record's built-in reflection capabilities to figure out how your models are associated.

一応Rails6.0でも動作しましたが、以下のような警告は表示されます。

Warning: Ignoring invalid model ActionText::RichText (table action_text_rich_texts does not exist) Warning: Ignoring invalid model ActionMailbox::InboundEmail (table action_mailbox_inbound_emails does not exist) Warning: Ignoring invalid model ActiveStorage::Blob (table active_storage_blobs does not exist) Warning: Ignoring invalid model ActiveStorage::Attachment (table active_storage_attachments does not exist)

graphvizのインストール

依存関係によりうまくgraphvizがinstallできない問題も起きます。 Dockerの場合はコンテナに入り、コマンドでgraphvizをインストールし、必要なパッケージを確認してからDockerfileを更新するのが吉です。

参考

まとめ

自動でやってくれるのはいいですね〜

しばらく使ってみて、うまみつらみを感じてみようと思います。