2012-04-28 72 views
2

我正在使用設計註冊的Rails應用程序。我使用單表繼承來管理用戶角色,similar to this。我有三個用戶型號User < ActiveRecord,Admin < UserCollaborator < User。協作者和管理員共享會話。我目前的問題是創建新用戶,用戶被保存到數據庫和user_signed_in?返回true,但由於某種原因,current_user返回nil。設計current_user當我創建新用戶時返回nil,Rails 3.2

當用戶創建自己的帳戶應該重定向到我AccountsController指數動作,看起來像這樣:

def index 
    @accounts = current_user.accounts 
end 

結果:

undefined method `accounts' for nil:NilClass 

相同的代碼工作時,我反而嘗試登錄。

我的路線看起來像這樣(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 

我也創建了我使用(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 

有誰知道是什麼原因造成的?

回答

0

我設法解決它通過定製after_sign_up_path_for,像這樣:

def after_sign_up_path_for(resource) 
    sign_in(resource) 
    accounts_path 
end 

讓我知道是否有更好的方式來做到這一點。

+0

有沒有想過這個?我知道這是幾年,但遇到類似的情況,並希望避免使用您的修復程序。它的簡單和將工作,但似乎你不應該 – MingMan 2017-08-04 18:54:58

相關問題