LoginSignup
5
3

More than 3 years have passed since last update.

rails webアプリケーション管理者権限でユーザーを削除する(delete)方法,deviseなしバージョン(初心者)

Last updated at Posted at 2019-09-27

(delete)ユーザー削除機能を実装

ネット情報ではログイン機能 gem deviseをを前提としたのが多く当方初心者な為、まぁまぁ時間を食った。
後々の私の様な初心者の為にRailsチュートリアルを中心に改めて自分なりにまとめて見た。

⒈管理者権限用カラムを作成

一般ユーザーと分ける為に管理者専用カラム作成。

$ rails generate migration add_admin_to_users admin:boolean

migrate
class AddAdminToUsers < ActiveRecord::Migration[5.0]
  def change
    add_column :users, :admin, :boolean, default: false
  end
end

$ rails db:migrate

⒉管理者権限を1人に与える

admin を true に。

db/seeds.rb
User.create!(name: "Exaple User",
             email: "example@railstutorial.org",
             password:                 "foobar",
             password_confirmation:    "foobar",
             admin: true )

$ rails db:migrate:reset

$ rails db:seed

③ログインユーザーが管理者ならパーシャルの横にdelete ボタンを表示

この!current_user?(user)は自分自身の2つ目のアカウントでは管理者権限は無効に。

db/app/views/users/_user.html.erb

<div>
  <%= gravatar_for user, size: 50 %>
  <%= link_to user.name, user %>
  <% if current_user.admin? && !current_user?(user) %>
    | <% link_to "delete" user, method: :delete,
                          data: {confirm: "You sure?"} %>
  <% end %>     
</div>

current_user? が使えるように定義

db/sessions/helper.rb

def current_user?(user)
  user == current_user
end

⒈ログインが前提なので、require_user_logged_inにdestroyを追加。
⒉管理者だけが削除できるように、admin_user, only: :destroyをbefore_actionに新たに作成。
⒊動作用destroyアクションを追加

db/user_controller.rb
before_action :require_user_logged_in, only: [:index, :show, :edit, :update, :destroy, :followings, :followers]
before_action :admin_user, only: :destroy #アクション前に事前確認用。


def destroy
  User.find(params[:id]).destroy
  flash[:success] = "ユーザー削除完了"
  redirect_to users_path
end

private

#管理者か確認。
def admin_user
  redirect_to(root_path) unless current_user.admin?
end

あとは実際に動作確認するだけ。

もしエラーが出たら、こちらも参照。

ユーザー削除するってことは、関連するデータの処理もどうするのか?
https://qiita.com/shutyan/items/05977055b2ce32c2e322

5
3
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
5
3