As the application administrator I want to be able to view who all has signed up for accounts in my application and the last time they signed in. This view and functionality isn’t built into devise, so we’re going to be coding it ourselves.
First step: Adding our Routes so we can add a users index with devise
First we’re going to need to create the appropriate route for our view. So in our routes.rb file we’ll add the following line:
config/routes.rb resources :users, only: [:index]
Then in our command line we’ll run
rake routes to ensure the appropriate route was created. Now we need to actually create a users controller and include an index method in it. We’ll navigate to app/controllers and create a new file. We’ll also add a before action to make sure that only users that have the admin column set to true can view this page (you can read about how to set admin accounts here).
app/controllers/users_controller.rb Class UsersController < ApplicationController before_action :check_admin, only: [:index] def index @users = User.all.order('LOWER(username)') end private def check_admin @checkUser = current_user @checkUser.admin == true end end
Next up: Creating our views for the users index
Now we’ll need to create the appropriate view file for our user index. First under
app/views we’ll create a folder:
app/views/users and then we’ll create our new view file in that folder:
app/views/users/index.html.erb <% @users.each do |user| %> <div class=""container"> <div class="panel panel-primary"> <div class="panel-heading"><%= user.username %></div> <div class="panel-body"> <ul> <li>Email: <%= user.email %></li> <li>User ID: <%= user.id %></li> <li>Last Signed In: <%= user.last_sign_in_at.strftime('%H:%M:%S %B, %d, %Y') %></li> </ul> </div> <div class=""panel-footer"></div> </div> </div> <% end %>
This will make your user index look like this (as long as you’re using bootstrap):
Finally: How to actually access our Users Index
In order to access the index you can place the following link anywhere you want:
<li><%= link_to("View Users", users_path) %></li>
I’ll be posting this week about how to make contextual views based on User account types so that only users with admin access can see certain features, and users with beta access can see others.