Step1 graphvizのインストール
brew install graphviz
GraphvizはAT&T研究所が開発したツールパッケージ。
グラフ構造を描画する便利なやつ。
Step2 gemの導入
gem 'rails-erd'
記述は以下の位置が良い。(本番環境では使用しないため。)
group :development, :test do gem 'rails-erd' end
bundle install を忘れずに。
Step3 モデルの作成・アソシエーションの記述
今回はUserモデルとArticleモデルを作成した。
マイグレーションファイルは以下の通り。
class CreateUsers < ActiveRecord::Migration[6.0] def change create_table :users do |t| t.string :nickname, null: false, default: "" t.string :email, null: false, default: "" t.string :encrypted_password, null: false, default: "" t.string :last_name, null: false t.string :first_name, null: false t.string :company t.string :department t.date :birth_date, null: false t.timestamps end end end
class CreateArticles < ActiveRecord::Migration[6.0] def change create_table :articles do |t| t.string :title, null: false t.text :content, null: false t.references :user, foreign_key: true t.timestamps end end end
アソシエーションは以下の通り。
class User < ApplicationRecord has_many :articles end
class Article < ApplicationRecord belongs_to :user end
rails db:migrateを忘れずに。
Step4 ER図の生成
bundle exec erd
ターミナルにて上記を実行する。
「erd.pdf」というファイルが生成されるので、Finderから開く。
(テキストエディターではPDFファイルが開けないことが多いため。)
アソシエーションも含んだER図が生成される。便利。
オプション 外部キーカラムも表示したい!
bundle exec erd --attributes=foreign_keys,content
上記のように「--attributes=foreign_keys,content」とオプションを記述することで、外部キーカラムも表示されるようになる。
⚠注意点!
- データベースが作成されている必要がある。(db:createを忘れずに!)
- テーブルが作成されている必要がある。(db:migrateを忘れずに!)
- アソシエーションはモデルに記述しておこう!