0
votes

I'm setting up an app (Rails 5) in which users have to be approved by an admin. I followed the instructions at https://github.com/plataformatec/devise/wiki/How-To%3a-Require-admin-to-activate-account-before-sign_in in setting everything up, but I'm getting a NoMethodError undefined method each' for nil:NilClass whenever I try to loop over @users. Here's my users_controller.rb

def index
  if params[:approved] == "false"
    @users = User.find_by_approved(false)
  else
     @users = User.all
  end
end

user model user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable, :confirmable

  def active_for_authentication?
    super && approved?
  end

  def inactive_message
    if !approved?
      :not_approved
    else
      super
    end
  end
end

routes.rb

Rails.application.routes.draw do
  devise_for :admins
  devise_for :users, except: [:index]
  resources :users, only: [:index]

  get 'home/index'

  get 'home/about'

  get 'home/products'

  get 'home/agents'

  get 'home/contact'

  get 'home/documents'

  get 'users/admin_page'

  root 'home#index'

end

and the table from my view at users/admin_page.html.erb

<%= link_to "All Users", :action => "index" %>|
<%= link_to "Users awaiting approval", :action => "index", :approved => "false" %>
 <table>
     <% @users.each do |user| %>
     <tr>
        <td><%= user.email %></td>
        <td><%= user.approved %></td>
        <td><%= link_to "Edit", edit_user_path(user) %></td>
     </tr>
     <% end %>
 </table>

I've looked around for other solutions or reasons why @users wouldn't be defined, but I can't find anything.

2
Try changing @users = User.find_by_approved(false) to @users = User.where(approved: false) and see if it fixes your problem - mrvncaragay
I just tried that and it's still showing up as nil. I also tried taking that part out completely and just defining it as @users = User.all and that showed up as undefined as well. - Jacob Jackson

2 Answers

0
votes

The find_by_ methods are intended to return a single object, or nil if none exists. You want the entire collection of users who have not yet been approved.

@users = User.where(approved: false)
0
votes

I figured it out. I misnamed my method in my UsersController. My view is named admin_page.rb but I named my method index. Thanks to everyone who responded.