これまでに作った機能について簡単にまとめていく。
今回は、
Gemを使用しない管理画面の作成
前提条件
ログイン機能があること
まだの方はこちら
使用モデル
Userモデル(adminは本記事中で設定)
カラム | データ型 | |
---|---|---|
1 | name | string |
2 | string | |
3 | password_digest | string |
4 | admin | boolean |
カラム追加
1 |
$ rails g migration: AddColumnToUser admin:boolean |
デフォルトでは、falseに設定。
1 2 3 4 5 |
class AddColumnToUsers < ActiveRecord::Migration[5.2] def change add_column :users, :admin, :boolean , default: false end end |
マイグレーションの実行
1 |
$ rails db:migrate |
コントローラーの作成
adminディレクトリ配下に作成し管理。
1 |
$ rails g controller admin::users |
アクセス制限の設定
admin(管理者)でない場合リダイレクト。
1 2 3 4 5 6 7 8 |
class Admin::UsersController < ApplicationController before_action :admin_user private def admin_user redirect_to root_path unless current_user.admin? end end |
ルーティングの設定
admin/usersのように設定。
1 2 3 |
namespace :admin do resources :users end |
アクションとviewを追加。
以上で作成完了