Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
9
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

@colorrabbit

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

症状

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
9
Help us understand the problem. What are the problem?