Muhammad Ateq Ejaz
Muhammad Ateq Ejaz

Reputation: 1865

Devise "<#User not initialized>" error

I have integrated devise in a pre-existing "User" Model. Here it is how it looks like

User.rb

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

include AstroModels::Users::Validation

when i browse any authentication page. i get following error

ActionView::Template::Error (undefined method `[]' for nil:NilClass):

I have debug it using <%resource.inspect%> , i get following error,

<#User not initialized>

on the following line

<%= form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f| %>

Also, i tried a stack overflow answer by changing

<%= form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f| %>

to

**<%= form_for(resource_name, :as => resource, :url => session_path(resource_name)) do |f| %>**

But doesn't seem work. Just for info i'm integrating devise in an application that uses rails4.

For just more iinfor i have following in my application helper file.

  def resource_name
    :user    
  end

  def resource

  @resource ||= User.new
  end

 def devise_mapping
  @devise_mapping ||= Devise.mappings[:user]
 end

Any suggestion/workaround would be great help thanks.

Upvotes: 0

Views: 415

Answers (2)

Muhammad Ateq Ejaz
Muhammad Ateq Ejaz

Reputation: 1865

In my case i was inheriting my custom User Model with ActiveRecord::Base class and by ActiveRecord::Base when we inherit any class with it we can not have our own initialize method in that custom model. So i commented out initialize method in my custom model and the error was gone.

Hope it will help you.

Upvotes: 2

Richard_G
Richard_G

Reputation: 4820

You didn't mention routes.rb or the views you need to create a session, which initializes user. Have you completed those tasks? You should start with the Devise installation generator to add in the code including initializers:

rails generate devise:install

routes.rb has to include devise_for that is set for your application. An example, not necessarily complete for you:

Sampleapp::Application.routes.draw do
  root :to => "home#index"
  devise_for :users, :controllers => {:registrations => "registrations"}
  resources :users
end

You can access the views in the Devise gem, or you can copy them to your own application so they can be customized like this:

rails generate devise:views  

This will provide app/views/devise views as well as app/views/layouts needed to login and create a session, among others.

Upvotes: 0

Related Questions