Admin User List
In this article, we will make a lists of users for our admin page. At the same time, we will configure our website redirect us to specific pages depending on the genre
of the user upon sign-in.
Admin::User Page
Let’s begin by making route resources :users
under admin
namespace.
# routes.rb
Rails.application.routes.draw do
# ...
+ namespace :admin do
+ resources :users
+ end
end
Then generate controller.
root@0122:/usr/src/app# rails g controller 'admin/users' index --skip-routes
create app/controllers/admin/users_controller.rb
invoke erb
create app/views/admin/users
create app/views/admin/users/index.html.erb
invoke helper
create app/helpers/admin/users_helper.rb
Get all users on your Admin::UsersConroller#index
.
# app/controllers/admin/users_controller.rb
class Admin::UsersController < ApplicationController
def index
+ @users = User.page params[:page]
end
end
Modify content of admin/users index view, display users in <table>
.
<!-- app/views/admin/users/index.html.erb -->
- <h1>Admin::Users#index</h1>
- <p>Find me in app/views/admin/users/index.html.erb</p>
+ <h1>Admin Users</h1>
+ <table class="table table-striped table-hover">
+ <thead>
+ <td>id</td>
+ <td>email</td>
+ <td>genre</td>
+ </thead>
+ <% @users.each do |user| %>
+ <tr>
+ <td><%= user.id %></td>
+ <td><%= user.email %></td>
+ <td><%= user.genre %></td>
+ </tr>
+ <% end %>
+ </table>
+
+ <%= paginate @users %>
Redirect Path
All that’s left now is changing the redirect path after user sign-in/sign-up.
Read Carefully
Devise have a method
after_sign_in_path_for
andafter_sign_up_path_for
that takes up aresource
argument. These methods let’s the developer decide where to redirect the user after they sign-in or sign-up.
Add after_sign_in_path_for
and after_sign_up_path_for
methods on our ApplicationController
.
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
+ def after_sign_up_path_for(resource)
+ after_sign_in_path_for(resource) if is_navigational_format?
+ end
+
+ def after_sign_in_path_for(resource)
+ if current_user.admin?
+ admin_users_path
+ else
+ posts_path
+ end
+ end
end
User will now be redirected Admin Users page if their genre
is admin, else they will be redirected to Posts page.
Read Carefully
Method
is_navigational_format?
is a devise controller helper that returns aboolean
. It returnstrue
if the format of request is supported by Rails, otherwise it will returnfalse
.
That’s all for Admin Users List.