13
20

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 3 years have passed since last update.

(2021年)Ruby on Rails 管理者(admin)ログイン作成

Posted at

###前提条件

  • deviseでcosutomerログインできること
ターミナル
$ rails g devise Admin
$ rails db:migrate

adminでログインするユーザー作成する。

db/seeds.rb
Admin.create!(
   email: 'admin@admin',
   password: 'testtest'
)
ターミナル
$ rails db:seed

adminのユーザーデータが入っているか確認する。

ターミナル
$ rails c
$ irb(main):001:0> Admin.all
$ irb(main):002:0> exit

次はviewとcontrollerの作成します。

ターミナル
$ rails g devise:views admins
$ rails g devise:controllers admins

ルーティングを編集をします。

config/routes.rb
devise_for :admins

devise_for :admins, controllers: {
  sessions: 'admins/sessions'
}

ログイン後のヘッダー画面を追加します。

application.html.erb
<% if customer_signed_in? %>
 <li>
  <%= link_to "ログアウト", destroy_customer_session_path, method: :delete %>
 </li>
<% elsif admin_signed_in? %>
 <li>
  <%= link_to "ログアウト", destroy_admin_session_path, method: :delete %>
 </li>
<% else %>
 <li>
  <%= link_to "新規登録", new_customer_registration_path %>
 </li>
 <li>
  <%= link_to "ログイン", new_customer_session_path %>
 </li>
<% end %>

管理者のログイン後ページ遷移とログアウト先を作成します。

controllers/admins/sessions_contoller.rb
protected
  def after_sign_in_path_for(resource)
    admin_items_path
  end

  def after_sign_out_path_for(resource)
    new_admin_session_path
  end
13
20
1

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
13
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?