[Rails] undefined method authenticate_user! workaround

20

summary

How to deal with situations where Ruby newbies can't find a function that is supposed to be there that is easy to fall into.

environment

  • Ruby 2.5.1
  • Ruby on Rails 5.2.1
  • devise 4.4.3
  • devise_token_auth 0.2.0

error

Since it uses devise_token_auth, it becomes a json format response. The response does not define a authenticate_user!. message is returned.

response
{
  "status": "error",
  "message": "undefined method `authenticate_user!' for #<Api::DummysController:0x0000000000000000>"
}

Routes and Controllers

It is characterized by the fact that mount_devise_token_auth_for belongs to the namespace API.

routes.rb
Rails.application.routes.draw do
  namespace :api do
    mount_devise_token_auth_for 'User', at: 'auth', controllers: {
      registrations: 'api/auth/registrations'
    }
    resources :dummys
  end
end
DummysController.rb
class Api::DummysController < ApplicationController
  before_action :authenticate_user! # ここでエラー

  # 省略
end

cause

The namespace in routes.rb caused a authenticate_user! definition error. When a devise_for called inside the mount_devise_token_auth_for is called, a authenticate_user is automatically generated. Therefore, if the namespace at the time of automatic creation is different from the usual, the authenticate_user generated will also be renamed according to the namespace.

There is a similar description in the official documentation, so let's check it once.

correspondence

This can be solved by changing the function name to correspond to the namespace.

  • before : authenticate_user
  • after : authenticate_api_user
DummysController.rb
class Api::DummysController < ApplicationController
  before_action :authenticate_api_user! # 変更点

  # 省略
end

supplement

Not only authenticate_user, but also current_user because it is a similar mechanism, The current_user needs to be changed to current_api_user.

bibliography

Share:
20
Masayuki Tsuji
Author by

Masayuki Tsuji

「仲間をサポートして次のステップへのキッカケを与える」を自身のミッションとしてスタートアップCTOで活動中。 技術ではAWS設計/構築、Vue.js, Nuxt.js, Python, Ruby, Javaなど幅広く携わる。 他、ペルソナ構想〜MVP検証、顧客インタビュー、そして論理的に考え現実主義のため、チーム内の意見を現実可能なラインまで落とし込むのが得意。

Updated on November 11, 2018