[Rails] deviseのサインアップを無効にする

スポンサーリンク

一瞬で終わる簡単な話だけど一応メモ。

シチュエーション

ユーザー登録の無いサイトだが運営者のデータ管理用にrails_adminなどの管理パネルを入れたい

そのページのアクセス権限をdevise+cancanなどで手軽に導入したい

deviseを普通に入れるとusers/sign_upのような誰でもユーザーを作れるルートが公開されてしまうのでこれを禁止したい

例えばこんな状況。

解決策

deviseの管理するmodel(userならapp/models/user.rb)から:registerableを抜く

berore:

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable, # ←これ
         :recoverable, :rememberable, :validatable
end

after:

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable,
         :recoverable, :rememberable, :validatable
end

rails routesコマンドでルート一覧を見ればsign_upが消えているのが確認できます。
でwebからのサインアップを禁止した後どう自分用ユーザーを作るかというと、rails consoleコマンドから

$ rails console
> user = User.new
> user.email = 'admin@example.com'
> user.password = 'password'
> user.save

のように作ればいいです。

コメント

タイトルとURLをコピーしました