LoginSignup
0
1

More than 1 year has passed since last update.

【Rails】初めてRailsの仕事をするときに知っておきたかったこと(基本篇)

Last updated at Posted at 2021-08-13

概要

突然、Railsを使っている仕事を任された時になにをすればいいだろうか?(私は困りました。。。)
仕様書やE-R図などのドキュメントの場所を聞く? どういった処理なのか先輩社員など詳しい人に聞く?
でもそんな都合の良いドキュメントはない。先輩も忙しくて聞く暇がない。
そんな時に自力である程度は調べる方法を記載する。

1.Railsのルーテイングを調べる

rails routesコマンドでルーテングを調べる。
基本的にRailsの作法を守っていればAPIに関連するコントローラーが割り出せる。

↓のコマンドで新たに作成したアプリ。

$ rails g scaffold Tweet title:string content:text

↑のコマンドで実行した場合のアプリのルーティング

$ rails routes
    Prefix Verb   URI Pattern                Controller#Action
    tweets GET    /tweets(.:format)          tweets#index
           POST   /tweets(.:format)          tweets#create
 new_tweet GET    /tweets/new(.:format)      tweets#new
edit_tweet GET    /tweets/:id/edit(.:format) tweets#edit
     tweet GET    /tweets/:id(.:format)      tweets#show
           PATCH  /tweets/:id(.:format)      tweets#update
           PUT    /tweets/:id(.:format)      tweets#update
           DELETE /tweets/:id(.:format)      tweets#destroy

Controller#ActionがAPIで使用されるコントローラーのアクションとなる
今回であれば、tweets_controller.rbのアクションが関連する。
より細かいルーティングに関してはroutes.rbを確認しよう。

2.モデルに紐つくアソシエーションを調べる

モデル名.reflect_on_all_associations
で各モデルに紐ついているアソシエーションを調べることができる。
これでモデル同士の関連を調べることができる(多対多、1対多など)

# 全部
$ Account.reflect_on_all_associations

# belongs_to だけ
$ Account.reflect_on_all_associations(:belongs_to)

# has_many だけ
$ Account.reflect_on_all_associations(:has_many)

# has_one だけ
$ Account.reflect_on_all_associations(:has_one) 

3.E-R図を自作する

2で関連性はわかったけれども、E-R図として全体を見れないと把握がきつい。。。
そんな時は自作しちゃいましょう。Rails ERDのgemでサクッとE-R図を作ってみましょう。

Graphviz(グラフビズ)のインストール

使用するには Graphviz が必要なため、UbuntuとMacでのインストール方法は以下になります。

Ubuntu

$ sudo apt-get install graphviz

Mac

Homebrewからインストールします。

$ brew install graphviz

Gemfileの設定

Gemfile
# 開発とテスト環境のGem指定

group :development, :test do
  gem 'rails-erd'
end

rails-erdのインストール

$ bundle install

コマンド実行

以下のコマンドをプロジェクトのディレクトリで実行します。
E-R図が作成できるはずです。

$ bundle exec erd

E-R図

E-R.png

まずは使用するAPIのルーティングとモデルのアソシエーションがわかれば、
どのように動いているかの確認ができるようになると思います。

参考文献

◇Rails のルーティング
https://railsguides.jp/routing.html

◇モデルに紐つくアソシエーション
https://api.rubyonrails.org/classes/ActiveRecord/Reflection/ClassMethods.html

◇rails-erd
https://github.com/voormedia/rails-erd

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1