[Rails-API] ユーザー新規登録機能を実装する

学習記録

はじめに

rails-APIにユーザー新規登録機能を実装しましょう。

ルーティング設定

post 'registration', to: 'registrations#create'

registrationsコントローラの作成

ユーザー新規登録機能の処理を担うregistrations_controller.rbを作成します。

# frozen_string_literal: true

module Api
  module V1
    class RegistrationsController < BaseController
      def create
        @user = User.new(user_params)

        if @user.save
          json_string = UserSerializer.new(@user).serialized_json
          render json: json_string
        else
          render_400(nil, @user.errors.full_messages)
        end
      end

      private

      def user_params
        params.require(:user).permit(:name, :email, :password)
      end
    end
  end
end

postmanで確認

registrations_controller.rb の、params.require(:user).permit(:name, :email, :password) ですが、require(:user)の部分を消さないと、エラーが起こり正しくデータが返ってきません。

Image from Gyazo

一時的に消して検証します。

def user_params
  params.permit(:name, :email, :password)
end
Image from Gyazo

今度は正しく返ってきています。

コメント

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