LoginSignup
8
6

More than 3 years have passed since last update.

管理者画面の作り方 admin Rails

Posted at

アプリの管理者と一般ユーザーで使える画面を分けたい!!

なぜこんなことがしたいか?
例:不適切なユーザーなどがいたら、管理者のみそのユーザーを削除したい。このようなケースを想定して管理者画面と一般ユーザー画面を作る必要があります。

もともとあったController(例:postscontroller)とは別に /admin のURLにアクセスすると、
postsの一覧が出るようにしましょう(こちらは管理者がpostを管理するための画面。一般ユーザーはアクセスできない)

1 . コントローラーを作成 参考

bundle exec rails g controller admin::posts

2 . routingを作成(indexも作成しといてください)

 get "/admin" => "admin/posts#index"
  namespace :admin do
    resources :posts
  end

3 . admin/posts/indexにposts/indexのコードコピー(scaffold)
ここで少し触ってみるとリンクを触ったところでエラー!!

<div id=list_index> 
<span><%= link_to 'Show', product %></span> 
<span><%= link_to 'Edit', edit_post_path(product) %></span> 
<span><%= link_to 'Destroy', post_path(product), method: :delete, data: { confirm: 'Are you sure?' } %></span> 

下記のように修正後エラー解消!link_toメソッドについての理解が必要
(https://web-camp.io/magazine/archives/16857)

<div id=list_index> 
<span><%= link_to 'Show', post_path(product) %></span> 
<span><%= link_to 'Edit', edit_admin_post_path(product) %></span> 
<span><%= link_to 'Destroy', admin_post_path(product), method: :delete, data: { confirm: 'Are you sure?' } %></span> 

4 . 管理者と一般ユーザーを定義する

enumでnormal一般ユーザー,staff管理者とし、staffのみが/adminに入れるようにしたい

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable
  has_many :posts
  enum role: { normal: 0, staff: 1 }
end

seed.rbで初期ユーザーを作っておくと確かめやすいです!

user1 = User.create!(id: 1, email: "user1@example.com", password: "password", name: "huuma", role: :normal)
user2 = User.create!(id: 2, email: "user2@example.com", password: "password", name: "gggg", role: :staff)
user3 = User.create!(id: 3, email: "user3@example.com", password: "password", name: "user3", role: :normal)

5 .どのように選別するかを考える (重要)
/adminに遷移する時、staffかそうでないかを判断しないといけない。
そこでbefore_actionを自分でAdmin::PostsController に定義する。


def admin_check
        unless user_signed_in? && current_user.role == :staff
            redirect_to root_path
            flash[:notice] = "管理者画面です"
        end
    end

ここで僕が陥っていた失敗を紹介します。一見行けそうに見えるが、これだと/adminで永遠ループしてしまいます。(リダイレクトループが止まらなかったという結果)

def admin_check
    if user_signed_in? && current_user.role == "staff"
        riderect_to new_admin_product_path
    else
        render action: :edit
        flash[:alert] = "管理者画面です"
    end
    end

redirect_toメソッドの理解も必要ですね!

8
6
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
8
6