設計と実装をRailsでシームレスに行う(ER図)

目的

ER図のメンテコストをなくす

実装に前倒しで着手する

前提

フレームワークにRailsを使用する

Railsの環境構築を行う

手順

1. 環境にgraphvizをインストールする
2. Gemfileにgemを指定する
3. Rakefileにタスクを定義する

1. graphvizをインストールする

# OSのディストリビューションに合わせて
yum install graphviz
 or
apt-get install graphviz
 or
brew install graphviz

2. Gemfileにgemを指定する


group :development do
 gem 'rails-erd'
end

3. Rakefileにタスクを定義する

require_relative 'config/application'

Rails.application.load_tasks

# migrateのタスクをフックする
Rake::Task['db:migrate'].enhance do
 if Rails.env.development?
   Rake::Task[:after_migrate].invoke
 end
end

# migrateの後のタスク
task :after_migrate do
 Rake::Task[:create_erd].invoke
end

# ER図を作成
task :create_erd do
 # attributes=foreign_keys,primary_keys,timestamp (属性は主キー、外部キー、タイムスタンプを表示)
 # sort=false (カラム名をアルファベット順にしない)
 # filename=hage-erd (ファイル名)
 # filetype=png (ファイル拡張子)
 sh 'bin/rake erd attributes=foreign_keys,primary_keys,content,timestamp sort=false filename=hage-erd filetype=png'
end

modelを生成し、必要なrelationを設定し、migrateを実行する

rails g model モデル名(s付けない) カラム名(idは自動生成されるので定義しない):型 × カラム数分

class User < ActiveRecord::Base
  has_many :books
end

class Book < ActiveRecord::Base
  belongs_to :user, class_name: 'User', foreign_key: 'user_id', optional: true
end

rails db:migrate

画像1


この記事が気に入ったらサポートをしてみませんか?