dougiebuckets
dougiebuckets

Reputation: 2453

Creating an Admin view w/ CRUD operations for Devise Users

I'm using Rails 4 w/ Devise for the first time and trying to build a view for Admins to lookup users and modify user attributes. Consequently, I've created a new boolean attribute, 'admin', to my Devise User model. However, this question is primarily concerned with building the admin view so the admin has CRUD operations that can be used on the different users.

In testing the 'show' view, I get the following error when trying to show a particular user's email address:

'undefined method `email' for nil:NilClass'

My admins_controller looks like this:

 class AdminsController < ApplicationController
  def index
    @users = User.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @users }
    end
  end

  def show
  end

end

The corresponding 'index' and 'show' views look like this:

'views/admins/index.html.erb'

    <h1>Listing users</h1>

<table>
  <tr>
    <th>User ID</th>
    <th>User Name</th>
    <th>Admin</th>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Address</th>
    <th>City</th>
    <th>State</th>
    <th>Zipcode</th>
  </tr>

<% @users.each do |user| %>
  <tr>
    <td><%= user.id %></td>
    <td><%= user.email %></td>
    <td><%= user.admin %></td>
    <td><%= user.first_name %></td>
    <td><%= user.last_name %></td>
    <td><%= user.address %></td>
    <td><%= user.city %></td>
    <td><%= user.state %></td>
    <td><%= user.zip %></td>
    <td><%= link_to 'Show', user %></td>
  </tr>s
<% end %>
</table>

'views/admins/show.html.erb'

<p id="notice"><%= notice %></p>

<p>
  <strong>Email:</strong>
  <%= @users.email %>
</p>

Does anyone have thoughts as to what is causing the error?

Upvotes: 1

Views: 2115

Answers (1)

randomor
randomor

Reputation: 5663

When you do resources admins in your route, the #index action is actually /admins/ no index needed. So when you do /admins/index, it's actually thinking you want go to show action with index mapped to params[:id]. You could use rake routes to see all your generated routes.

Upvotes: 1

Related Questions