Ruby on rails 我应该如何使用Rails实现多个模型的身份验证/授权?

Ruby on rails 我应该如何使用Rails实现多个模型的身份验证/授权?,ruby-on-rails,authentication,Ruby On Rails,Authentication,我的应用程序中有3种用户:俱乐部、个人和管理员。每一个都非常不同,这意味着它们除了身份验证数据之外几乎不共享任何属性,因此我宁愿使用3种不同的模型。另外,我想使用Authlogic为所有这些类型的用户启用单一身份验证模型,并使用CanCan处理授权 起初我想到了这样的事情 class User < ActiveRecord::Base # This class has the email and password in order to be authenticated with Aut

我的应用程序中有3种用户:俱乐部、个人和管理员。每一个都非常不同,这意味着它们除了身份验证数据之外几乎不共享任何属性,因此我宁愿使用3种不同的模型。另外,我想使用Authlogic为所有这些类型的用户启用单一身份验证模型,并使用CanCan处理授权

起初我想到了这样的事情

class User < ActiveRecord::Base
 # This class has the email and password in order to be authenticated with Authlogic
end
class用户
对于每一个我都会有

class Club < User end
class Admin < User end
class Club<用户端
类管理<用户端
但是,用户表将与其他类型用户的所有列混杂在一起,它们将保持为空

另一个选择是

class User < ActiveRecord::Base
 # This class has the email and password in order to be authenticated with Authlogic
 belongs_to :role, :polymorphic => true
end
class用户true
结束
对于每种类型的用户,都会分配一个角色。问题是访问方法的属性类似于
user.role.logo
。我认为解决这个问题的一种方法是使用委托,但我仍然不知道这是否是最好的选择


问题是,你建议我如何实施这一点?最好的方法是什么?

我认为您正在尝试实现基于角色的授权。请查看中的wiki页面 坎坎


正如您所建议的,我将创建一个用户模型来处理身份验证。然后可以在用户模型和角色模型之间创建一对一的多态关系。您的用户模型必须包括role_type(字符串)和role_id(整数)属性

User.rb
你真的需要3种不同的型号吗?我的意思是除了授权之外的其他原因…原因是这3类用户彼此非常不同,所以我不喜欢数据库中有一堆空字段的单一模型。
class User < ActiveRecord::Base
  belongs_to :role, :polymorphic => true
end
class Admin < ActiveRecord::Base
  has_one :role
end
User.first.role.is_a? Admin
=> true
User.first.role.last_name
=> "Smith"