はじめに
ユーザーが認証済み(ログイン済み)の状態で基本的な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

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/authentication
にemail
とpassword
のパラメータを渡してリクエストすると、ユーザーのデータが返ってきます。

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

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

記事一覧データ取得(indexアクション確認)
Access Token
を渡してGETメソッドでlocalhost:3000/api/v1/user/articles
にアクセスします。

ちゃんとユーザー1の記事一覧データが取れてますね。
記事の作成(createアクション確認)
Access Token
とパラメータを渡してPOSTメソッドでlocalhost:3000/api/v1/user/articles
にアクセスします。

記事の更新(updateアクション確認)
Access Token
とパラメータを渡してPATCHメソッドでlocalhost:3000/api/v1/user/articles/12
にアクセスします。

ちゃんとcontents
が更新されています。
記事削除(destroyアクション確認)
Access Token
を渡してDELETEメソッドでlocalhost:3000/api/v1/user/articles/12
にアクセスします。

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



コメント