SilverNightaFall
SilverNightaFall

Reputation: 4170

uninitialized constant UsersController::User

Where do I initialize the constant? I thought it was just in the controller.

Error

uninitialized constant UsersController::User

Users Controller

 class UsersController < ApplicationController
      def show
        @user = User.find(params[:id])
      end
      def new
      end
    end

routes

SampleApp::Application.routes.draw do

  get "users/new"
 resources :users
  root to: 'static_pages#home'

  match '/signup', to: 'users#new'

  match '/help', to: 'static_pages#help'
  match '/about', to: 'static_pages#about'
  match '/contact', to: 'static_pages#contact'

user.rb

 class AdminUser < ActiveRecord::Base
      attr_accessible :name, :email, :password, :password_confirmation
      has_secure_password
      before_save { |user| user.email = email.downcase }
      validates :name, presence: true, length: { maximum: 50 }
      VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
      validates :email, presence: true,
      format: { with: VALID_EMAIL_REGEX },
      uniqueness: { case_sensitive: false }
      validates :password, presence: true, length: { minimum: 6 }
      validates :password_confirmation, presence: true
    end

This might help I am also getting

The action 'index' could not be found for UsersController

when I go to the users page, but when I go to users/1 I get the above error.

Upvotes: 0

Views: 13226

Answers (1)

x1a4
x1a4

Reputation: 19475

You have a couple of problems here -

  1. Your AdminUser model should be called User, as it's defined in user.rb, and your UsersController is trying to find them, which is why you get the uninitialized constant UsersController::User error. The controller will not define the User class for you.

  2. You haven't defined an index action in UsersController, but you've defined a route for it. When you declare a resource in your routes.rb file, Rails will create 7 routes by default, which point to specific actions in the controller - index, show, new, edit, create, update, and delete. You can prevent Rails from defining one or more of the routes, via the :only parameter - e.g. resources :users, :only => [:new, :show] You can see the routes that are defined, as well as the controller actions they will call with rake routes. http://localhost:3000/users will hit the UsersController#index action by default, while http://localhost:3000/users/1 will hit the UsersController#show action by default, passing 1 as the id param.

Upvotes: 7

Related Questions