【问题标题】:rails devise - how to have 2 devise authentications for two different user models?rails devise - 如何为两个不同的用户模型进行 2 个设计身份验证?
【发布时间】:2026-02-05 00:05:01
【问题描述】:

我们有 admin_users 和普通用户,他们都有单独的表、模型和设计登录。

仅对一个用户表使用 devise 并为角色使用 cancan 可能更有意义,但该应用程序已使用两个单独的用户表创建,此时无法更改它们。

管理员用户功能(包括登录)运行正常。 最初的标准用户访问仅通过基于链接和令牌的身份验证,但需要更改。

在我们拥有的路线中

devise_for :admin_users, ActiveAdmin::Devise.config  
devise_for :users
resources :users, :only => [:update, :edit]

所以我添加了用户资源的根路径,如设计文档所示,作为成功登录的位置:

devise_for :admin_users, ActiveAdmin::Devise.config  
devise_for :users
resources :users, :only => [:update, :edit] do
  root to: "practitioner_activities#welcome"
end  

然后我也尝试删除 only => 例如

devise_for :admin_users, ActiveAdmin::Devise.config  
devise_for :users
resources :users do
  root to: "practitioner_activities#welcome"
end  

对于我更改的(常规)用户模型:

devise :token_authenticatable,

还有:

devise :token_authenticatable, # token login still permitted.  
       :database_authenticatable, :recoverable, :rememberable, 
       :trackable, :validatable
       # Not sure if these will make a difference but they are like this in other apps.

但不是重定向到从业者活动#welcome,而是将用户发送回登录屏幕。

我注意到控制台中为登录 POST 记录的第一行使用的是 AdminUser 模型,而不是 User 模型。知道如何解决吗?

Started POST "/" for 127.0.0.1 at 2012-08-23 13:54:50 -0400
Processing by HelpController#show as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"28iGxAB+URoIKoBQtPizGAosJoZ/V7Vko1w/bYMvesE=", "new_user_session_path"=>{"email"=>"Borger.Cathy@meridianschools.o
rg", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Sign In"}
  AdminUser Load (0.4ms)  SELECT "admin_users".* FROM "admin_users" WHERE "admin_users"."id" = 1 LIMIT 1

登录表单本身是:

= semantic_form_for(:new_user_session_path, 
  :html => {:id => "session_new"}) do|f| 

      = f.inputs do
        = f.input :email, :label => "Username"
        = f.input :password
        = f.input :remember_me, :as => :boolean, :if =>  false  
        = f.commit_button "Sign In"

【问题讨论】:

  • 出于好奇,您是否尝试过在devise_for :admin_users 之前声明devise_for :users
  • 是的,很棒的想法,即我也有同样的想法;)是的,我试过了,但没有帮助。我发现的一件事是 application_controller 正在检查 current_admin_user.present?失败了,我可以使用not current_admin_user &= ''

标签: ruby-on-rails authentication devise token cancan


【解决方案1】:

最后主要的事情是再次设计生成器,然后编辑设计视图。

【讨论】: