[Rails-API] ログインユーザーによるCRUD処理

学習記録

はじめに

ユーザーが認証済み(ログイン済み)の状態で基本的なCRUD機能を実装しましょう。

ルーティング設定

moduleを使うと、下記のようになります。

  • URLは変わらない
  • ファイル構成は指定のパスになる

今回の場合はresource :user, only: [] do end の配下にあるので、結果的にURLもuser/articles となっています。

resources :articles, only: %i[index show]
      resource :authentication, only: %i[create]
      resource :registration, only: %i[create]

      resource :user, only: [] do
        scope module: :user do
          resources :articles, only: %i[index create update destroy]
        end
      end
    end
  end
end
Image from Gyazo

user/articlesコントローラー

ユーザー認証した際の記事に対するCRUD処理を記述します。このコントローラの処理は、ユーザーログインしないとエラーになる想定です。

# frozen_string_literal: true

module Api
  module V1
    class User::ArticlesController < BaseController
      before_action :set_articles, only: :index
      before_action :set_article, only: %i[show update destroy]

      def index
        json_string = ArticleSerializer.new(@articles).serialized_json

        render json: json_string
      end

      def create
        article = current_user.articles.new(article_params)

        if article.save
          json_string = ArticleSerializer.new(article).serialized_json
          render json: json_string
        else
          render_400(nil, article.errors.full_messages)
        end
      end

      def update
        if @article.update(article_params)
          json_string = ArticleSerializer.new(@article).serialized_json
          render json: json_string
        else
          render_400(nil, article.errors.full_messages)
        end
      end

      def destroy
        @article.destroy!
        set_articles
        json_string = ArticleSerializer.new(@articles).serialized_json

        render json: json_string
      end

      private

      def set_article
        @article = current_user.articles.find(params[:id])
      end

      def set_articles
        @articles = current_user.articles
      end

      def article_params
        params.require(:article).permit(:title, :contents, :status)
      end
    end
  end
end

Userに絶対位置を指定

絶対位置指定を行う。User.newのように直接クラス名を書くと相対指定になるため、その呼出し元から最も近く、呼び出し元の同階層か、それより上の階層にあるクラスを参照します。 今回の場合は、User.newのままだとapi/v1/user/ と勘違いしてしまい、バグの原因となってしますことがあります。 絶対位置の指定は下記の通り、::(ダブルコロン)を先頭につけるだけで解決します。

def create
  @user = ::User.new(user_params)

postmanで確認

access_token を確認

POST でapi/v1/authenticationemailpassword のパラメータを渡してリクエストすると、ユーザーのデータが返ってきます。

Image from Gyazo

Headersタブの中を見ると、Access Tokenが入っているのが確認できます。これはユーザーid: 1 のAccess Tokenですので、これをリクエストの際に使うのでコピーします。

Image from Gyazo

access_token を渡すやり方

ログインした状態を再現するためには、AuthorizationタブのTypeをBearer Tokenを選んで、Tokenのフォームに先程コピーしたaccess_tokenを入れます。これでid: 1 のユーザーでログインしたことになります。

Image from Gyazo

記事一覧データ取得(indexアクション確認)

Access Tokenを渡してGETメソッドでlocalhost:3000/api/v1/user/articlesにアクセスします。

Image from Gyazo

ちゃんとユーザー1の記事一覧データが取れてますね。

記事の作成(createアクション確認)

Access Token とパラメータを渡してPOSTメソッドでlocalhost:3000/api/v1/user/articlesにアクセスします。

Image from Gyazo

記事の更新(updateアクション確認)

Access Token とパラメータを渡してPATCHメソッドでlocalhost:3000/api/v1/user/articles/12にアクセスします。

Image from Gyazo

ちゃんとcontentsが更新されています。

記事削除(destroyアクション確認)

Access Token を渡してDELETEメソッドでlocalhost:3000/api/v1/user/articles/12にアクセスします。

Image from Gyazo

ちゃんと削除されています。

参考

APIテストの書き方と共通テストの書き方 - Qiita
APIのテスト APIのテストに置いて、何をテストするのかというと、 レスポンスのステータスコードと実際のデータを含んだレスポンスボディをテストする。 ◆ステータスコード APIによって返されるステータスコードは通常以下の4つに分類...
Railsのroutingにおけるscope / namespace / module の違い - Qiita
はじめに 以前書いた、下記の続き。 今回は、Railsのroutingにおけるscope / namespace...
Ruby: クラス名の先頭につける :: (先頭二重コロン) は何?

コメント

タイトルとURLをコピーしました