LoginSignup
6
9

More than 5 years have passed since last update.

RailsでJSON APIのバックエンドを作っていたら、Deviseの認証周りで422 Unprocessable Entityエラーを吐いてしまった場合

Last updated at Posted at 2015-05-12

症状

RailsでJSON API用のバックエンド(管理画面はactive adminを利用し、そこだけはhtmlを利用)を作っています。
認証周りにDeviseを利用しました。
Routingは↓な感じで。

config/routes.rb
  namespace :api, format: 'json' do
    namespace :v1 do
      devise_for :users, controllers: {
        sessions:      'api/v1/users/sessions',
        registrations: 'api/v1/users/registrations',
        passwords:     'api/v1/users/passwords'
      }
    end
  end

で以下の様なテストをしました。

$ curl -H "Content-Type: application/json" -d '{"user":{"email":"hoge@hoge.hoge","password":"12345678"}}' -X POST http://localhost:3000/api/v1/users

結果↓

{"errors":{"email":["can't be blank"],"password":["can't be blank"]}}

対応

app/controllers/api/v1/registration_controller.rb

def sign_up_params
  params.require(:user).permit(:email, :password, :password_confirmation)
end

def create
  build_resource(sign_up_params)
  super
end

createは自前でコードを書いてもいいのですが、とにかくこれでうまくいきました。

curl -H "Content-Type: application/json" -d '{"user":{"email":"hoge@hoge.hoge","password":"12345678"}}' -X POST http://localhost:3000/api/v1/users
{"id":1,"email":"hoge@hoge.hoge","authentication_token":null,"created_at":"2015-04-12T09:41:31.842Z","updated_at":"2015-04-12T09:41:31.881Z"}%

References

6
9
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
6
9