LoginSignup
2
0

More than 1 year has passed since last update.

RailsでAPIを使用した開発の流れとチートシート(個人的なメモ)

Posted at

Railsの学習で学んだことを個人的な備忘録として残しておきます。
誰かの役に立てば幸いです。

◆Ruby on Railsを使ってAPIのエンドポイントを実装するための基本的な手順。

①新規Railsプロジェクトの作成:

まずは新規のRailsプロジェクトを作成します。
API専用のアプリケーションを作成する場合は、--apiオプションを指定します。
以下のコマンドでプロジェクトを作成できます。

rails new my_api --api

②ルーティングの設定:

config/routes.rb ファイルにてルーティングを設定します。
例えば、users リソースに対するエンドポイントを設定する場合は以下のように書くことができます。

Rails.application.routes.draw do
 resources:users
end

③モデルの作成:

必要なモデルを作成します。以下のコマンドでUserモデルを作成します。

rails g model User name:string email:string

④データベースマイグレーション:

モデルの作成後、データベースのマイグレーションを実行します。

rails db:migrate

⑤コントローラの作成:

APIのロジックを処理するために必要なコントローラを作成します。
以下のコマンドでUsersコントローラを作成します。

rails g controller Users

⑥アクションの定義:

コントローラに必要なアクション(index, show, create, update, destroyなど)を定義します。
各アクションでは、リクエストを処理して適切なレスポンスを返すロジックを実装します。

⑦データのシリアライゼーション:

RailsにはActiveModel::Serializersなどのgemを使用して、データをJSONにシリアライズする機能があります。
これを利用して、APIから返すデータ形式を制御します。

・Gemfile
gem'active_model_serializers'

・コマンドライン
bundle install
rails g serializerArticletitle description body

・app/serializers/article_serializer.rb
classArticleSerializer<ActiveModel::Serializer
attributes:id,:title,:description,:body
end

⑧エラーハンドリング:

APIではエラーハンドリングも重要な部分です。
例外を適切に捕捉して、適切なステータスコードとエラーメッセージを含むレスポンスを返すようにします。

・app/controllers/application_controller.rb
rescue_fromActiveRecord::RecordNotFound,with::not_found

private

defnot_found
renderjson:{error:'Not found'},status::not_found
end

⑨テストの作成:

APIの動作を保証するためにテストを作成します。
RailsではMiniTestがデフォルトで組み込まれていますが、RSpecを使うことも多いです。

・Gemfile
group:development,:testdo
gem'rspec-rails'
end

・コマンドライン
bundle install
rails generaterspec:install
・ファイルを生成 (次のコントローラーはモデルやビューに変えられる)
rails generate rspec:controller articles

・spec/controllers/articles_controller_spec.rb
require'rails_helper'

RSpec.describeArticlesController,type::controllerdo
describe'GET #show'do
テストの詳細を記述
end
他のメソッドについても同様に記述
end

⑩ドキュメンテーション:

APIを使用するためのドキュメンテーションを作成します。
APIのエンドポイント、パラメータ、レスポンス形式などを明記します。

◆Railsチートシート

新規プロジェクトの作成
rails new my_project

サーバーの起動
rails server#またはrails s

コンソールの起動
rails console#またはrails c

データベースの作成
rails db:create

データベースマイグレーション
rails db:migrate

マイグレーションのロールバック
rails db:rollback

マイグレーションのステータス確認
rails db:migrate:status

モデルの作成
rails generate model User name:string email:string

コントローラーの作成
rails generate controller Users index show

ルートの表示
rails routes

テストの実行
rails test

アセットのプリコンパイル
rails assets:precompile

シークレットキーの生成
rails secret

タスクの一覧表示
rails -T

◆アクションコントローラーのAPIコード(チートシート)

・クラス名
class ModelNameController < ApplicationController

・セットアップ: レコードを取得する前に実行
before_action :set_model_name, only: [:show, :update, :destroy]

・レコードの作成
・POST /model_name_plural
def create
@model_name = ModelName.new(model_name_params)

・レコードが保存できれば、レコードをJSONとして返す
・保存できなければ、エラーメッセージを返す
if @model_name.save
render json: @model_name, status: :create
else
render json: @model_name.errors, status: :unprocessable_entity
end
end

・レコードの取得
・GET /model_name_plural/:id
def show
render json: @model_name
end

・レコードの更新
#PUT /model_name_plural/:id
def update
レコードが更新できれば、レコードをJSONとして返す
更新できなければ、エラーメッセージを返す
if @model_name.update(model_name_params)
render json: @model_name
else
render json: @model_name.errors, status: :unprocessable_entity
end
end

レコードの削除
DELETE /model_name_plural/:id
def destroy
@model_name.destroy
end

private
レコードを取得するためのメソッド
def set_model_name
@model_name = ModelName.find(params[:id])
end

許可されたパラメータのリスト
def model_name_params
params.require(:model_name).permit(:attribute_1, :attribute_2, ...)
end

ここで ModelName、 model_name、 model_name_plural、 attribute_1、 attribute_2 などは
具体的なモデル名や属性に置き換えます。

例えば、ArticlesControllerの場合:
ModelName → Article
model_name → article
model_name_plural → articles
attribute_1, attribute_2, ... → title, description, body

2
0
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
2
0