Devise current_user returns nil when I create new users, Rails 3.2

1,396 views
Skip to first unread message

Anders

unread,
Apr 28, 2012, 3:52:19 PM4/28/12
to plataforma...@googlegroups.com
Hello, 

I asked a similar question on Stackoverflow, but I'm trying my luck here as well.

I'm working on a Rails app where I use Devise for registrations. I use single table inheritance for managing user roles, similar to this. I have three User models User < ActiveRecordAdmin < User and Collaborator < User. Collaborator and Admins share sessions. My current problem is with creating new users, the User is saved to the database and user_signed_in? returns true, but current_user returns nil for some reason.

When User creates their accounts it should redirect to my AccountsController index action which looks like this:

def index
 
@accounts = current_user.accounts
end

results in:

undefined method `accounts' for nil:NilClass

The same code works when I instead try to sign in.

My routes looks like this (as of):

devise_for :users, :controllers => {:sessions  => 'sessions'}, :skip => [:registrations] do
  delete
'/logout', :to => 'sessions#destroy', :as => :destroy_user_session
  get
'/sign_in', :to => 'sessions#new', :as => :new_user_session
  post
'/sign_in', :to => 'sessions#create', :as => :user_session
end
devise_for
:admins, :controllers => {:registrations  => 'admins/registrations'}, :skip => :sessions do
  get
'/sign_up', :to => 'admins/registrations#new', :as => :new_admin
  post
'/sign_up', :to => 'admins/registrations#create', :as => :admin
end
devise_for
:collaborators, :controllers => {:registrations  => 'collaborators/registrations'}, :skip => :sessions

I have also created some helper method that I use (the same as of):

# New Version using dynamic methods
 
%w(Collaborator Admin).each do |k|
  define_method
"current_#{k.underscore}" do
    current_user
if current_user.is_a?(k.constantize)
 
end

  define_method
"authenticate_#{k.underscore}!" do |opts={}|
    send
("current_#{k.underscore}") || not_authorized
 
end
end

def after_sign_in_path_for(resource)
 
if resource.is_a?(User)
    accounts_path
 
else
   
super
 
end
end

def after_sign_up_path_for(resource)
  accounts_path
end


I have a custom registrations controller that looks like this:

class Admins::RegistrationsController < Devise::RegistrationsController

  prepend_before_filter :require_no_authentication, :only => [ :new, :create ]

  

  # GET /resource/sign_up

  def new

    resource = build_resource({})

    account = resource.accounts.build  

    respond_with resource

end

Any tips on how to solve this would be great. 

Thanks.

Anders

unread,
Apr 28, 2012, 5:10:38 PM4/28/12
to plataforma...@googlegroups.com
I managed to solve it by customizing after_sign_up_path_for, like this:

    def after_sign_up_path_for(resource)
      sign_in(resource)
      accounts_path 
    end

Let me know if there is a better way to do it. 
Reply all
Reply to author
Forward
0 new messages