Search code examples
ruby-on-railsmodel-view-controllerdevise

Rails: Creating an index view for a devise user


This is a new project, so scraping and restarting would be easy if someone has advice in that direction. Essentially I created users with devise by using:

rails generate devise users

But now I want to create a route to something like a users#index page to display all the users. I couldn't find any routes that seemed like they were applicable when i ran rake routes

My next thought was to use rails generate scaffold user to try and generate such views and controller functions. This didn't work.

I'm relatively new to rails, but have a pretty general grasp of it. I've just started using devise, so that part confuses me most, I'm using it for validation. I have looked around for help and have studied the devise page quite a bit, but to no avail.

Just some extra info. When I try the route http://localhost:3000/users I get uninitialized constant UsersController but when I added a users controller it just complained about something else. I've tried several other things but don't want to dilute the question by going into all of them.


Solution

  • Devise hides its own controllers and views in the gem library directory. You can pull the views into your project for editing, but there's nothing similar for controllers. See the Devise documentation for some examples.

    It's pretty easy to generate your own controller and views for this:

    config/routes.rb:

    # NOTE: put this after the 'devise_for :users' line
    resources :users, only: [:index]
    

    app/controllers/users_controller.rb:

    class UsersController < ApplicationController
    
      def index
        @users = User.all
      end
    
    end
    

    app/views/users/index.html.erb:

    <ul>
      <% @users.each do |user| %>
        <li><%= user.name %></li>
      <% end %>
    </ul>
    

    This is a minimalist example that should work for you.

    You might want to consider using ActiveAdmin, if you don't need to style it like the public portions of your app. Saves you the trouble of coding, styling, and securing a lot of basic record management utlities that apps need. I use ActiveAdmin and then roll my own controllers/views/routes as above for presenting a user list in the public portions of the app.