我正在使用Rails应用程序,我使用Devise进行注册。我使用单表继承来管理用户角色similar to this。我有三个用户模型User < ActiveRecord
,Admin < User
和Collaborator < User
。协作者和管理员共享会话。我目前的问题是创建新用户,用户是保存到数据库还是user_signed_in?返回true,但current_user由于某种原因返回nil。
当用户创建帐户时,它应该重定向到我的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 :(得分:0)
我设法通过自定义after_sign_up_path_for来解决它,如下所示:
def after_sign_up_path_for(resource)
sign_in(resource)
accounts_path
end
如果有更好的方法,请告诉我。