ApiKeyによるAPIの認証を実装 - Rails技術ブログの続き。
①scaffoldでコントローラーを作成。
$ rails g scaffold_controller api::v1::user::articles
②ルーティングを設定。
Rails.application.routes.draw do namespace :api, format: 'json' do namespace :v1 do resources :articles, only: %i[index show] resource :authentication, only: %i[create] resource :registration, only: %i[create] namespace :user do resources :articles end end end end
③コントローラーを設定。
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 show options = { include: %i[user 'user.name' 'user.email'] } json_string = ArticleSerializer.new(@article, options).serialized_json render json: json_string end def create article = current_user.articles.build(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! response = { success: 'The article has been deleted' } render json: response, status: :ok 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) end end end end
※registrationsコントローラーの一部を編集。
def create # @user = User.new(user_params) # ↓ @user = ::User.new(user_params) if @user.save json_string = UserSerializer.new(@user).serialized_json set_access_token!(@user) render json: json_string else render_400(nil, @user.errors.full_messages) end end
railsはクラス名を自動解決してくれたりするので、場合によってはうまく解決出来ないケースがある。
参考記事:
いつも忘れる「Railsのgenerateコマンド」の備忘録 - maeharinの日記
namespaceの重複 - Qiita
Railsのルーティングの種類と要点まとめ - Qiita