RailsでDevise使った上でAPI作ろうとした話

Devise(GitHub - plataformatec/devise: Flexible authentication solution for Rails with Warden.)はユーザ登録・ログイン関係をよしなにやってくれるけど、フロントエンド用のAPI作ろうと思うと苦労する
ちょっと調べた感じだと色々書かないといけないっぽくて、それは嫌なので雑にハックした



app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  respond_to :html, :json
  protect_from_forgery with: :exception, unless: -> { request.format.json? }
end

config/routes.rb

namespace :v1, defaults: { format: 'json' } do
  devise_scope :user do
    resources :registrations, only: [:create]
  end
end

app/controllers/v1/registrations_controller.rb

class V1::RegistrationsController < Devise::RegistrationsController
  def create
    # 好きな処理
    super
  end

  def render(*args)
    super
  end
end

ApplicationControllerCSRF対策されているのをjsonのときは例外として、respond_toで一括してjsonを返せるようにしておく
Devise::RegistrationsControllerを継承した登録用コントローラ作って、routes.rbではdevise_scopeで指定しておく(お決まりのuserモデル作ってる前提)

これで/v1/registrationsへのアクセスにはjsonを返してくれるようになる
deviseが返すjsonそのままが嫌だったら、V1::RegistrationsControllerでrender(*args)をいじればいい