我知道这是一个非常古老的问题,但也许在 2019 年,Devise 支持devise_group对现在的人会有帮助。
Thins 使得使用多个 Devise 模型变得非常容易。我有三种不同的设计模型,如下所示:
用户.rb
class User < ApplicationRecord
has_many :messages
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable
end
组织者.rb
class Organizer < ApplicationRecord
has_one :organizer_profile, dependent: :destroy, autosave: true, inverse_of: :organizer
has_many :brochures, dependent: :destroy
has_many :messages, as: :messageable
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable
end
赞助商.rb
class Sponsor < ApplicationRecord
has_one :sponsor_profile, dependent: :destroy, autosave: true, inverse_of: :sponsor
has_many :sponsorings
has_many :brochures, through: :sponsorings
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable
scope :approved, -> { where(approved: true) }
# Allow saving of attributes on associated records through the parent,
# :autosave option is automatically enabled on every association
accepts_nested_attributes_for :sponsor_profile
end
路线.rb
Rails.application.routes.draw do
# Deviseable resources
devise_for :organizers, controllers: {registrations: "organizers/registrations"}
devise_for :sponsors, controllers: {registrations: "sponsors/registrations"}
devise_for :users
root "welcome#index"
end
现在我不能用同样的authenticate_user!
,user_signed_in?
甚至current_user
。那么现在,我如何知道是否有用户登录?我们可能需要做类似user_signed_in? || organizer_signed_in? || sponsor_signed_in?
的事情,但重复代码太多了。
由于devise_group
选项,我们可以简化此工作流程!
在你application_controller.rb
添加这个:
class ApplicationController < ActionController::Base
# Devise working with multiple models.
# Define authentication filters and accessor helpers for a group of mappings.
devise_group :member, contains: [:organizer, :sponsor, :user]
private
def pundit_user
# Make Pundit to use whichever Devise model [Organizer, Sponsor, User] as the 'current_user'
# Just by using the offered helper method from Devise, 'devise_group' feature
current_member
end
end
现在您可以使用通用助手authenticate_member!
,member_signed_in?
甚至current_member
在需要时验证任何设计用户。或者,您仍然可以像往常一样为每种类型的 Devise 用户提供用户分离的帮助程序。
希望它对某人有用!