0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【devise_token_auth】NoMethodError: undefined method `devise' for User:Class 解消法【Rails】

Last updated at Posted at 2023-03-13

状況

Railsアプリケーションにdevise_token_authを導入するために次の手順を実行しました。

Gemfile
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby "3.2.1"

gem "rails", "~> 7.0.4", ">= 7.0.4.2"

gem "mysql2", "~> 0.5"

gem "puma", "~> 5.0"

gem "tzinfo-data", platforms: %i[mingw mswin x64_mingw jruby]

gem "bootsnap", require: false

gem "rack-cors", "~> 2.0"

# 以下を追加
gem "devise_token_auth", "~> 1.2"

...
terminal
$ bundle install

$ rails g devise_token_auth:install User auth
      create  config/initializers/devise_token_auth.rb
      insert  app/controllers/application_controller.rb
        gsub  config/routes.rb
      create  db/migrate/000000000000_devise_token_auth_create_users.rb
      create  app/models/user.rb

編集が必要なファイルを編集した後にrails db:migrateを実行したところ次のようにエラーとなりました。

terminal
$ rails db:migrate                    
rails aborted!
NoMethodError: undefined method `devise' for User:Class
/home/ruby/app-name/app/models/user.rb:5:in `<class:User>'
/home/ruby/app-name/app/models/user.rb:1:in `<main>'
/home/ruby/app-name/config/routes.rb:4:in `block (3 levels) in <main>'
/home/ruby/app-name/config/routes.rb:3:in `block (2 levels) in <main>'
/home/ruby/app-name/config/routes.rb:2:in `block in <main>'
/home/ruby/app-name/config/routes.rb:1:in `<main>'
/home/ruby/app-name/config/environment.rb:5:in `<main>'
Tasks: TOP => db:migrate => db:load_config => environment
(See full trace by running task with --trace)

解決法

次のようにapp/models/user.rbextends Devise::Modelsを追記することでエラーが解消しました。

app/modules/user.rb
class User < ApplicationRecord
  extend Devise::Models
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  include DeviseTokenAuth::Concerns::User
end

または、config/initializers/devise.rbに以下を追記します。

config/initializers/devise.rb
Devise.setup do |config|
  require "devise/orm/active_record"
end

参考

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?