不同用户类型的Ruby on Rails [英] Ruby on rails with different user types
问题描述
我正在尝试构建一个具有不同类型用户的应用程序,我正在使用authlogic进行用户身份验证.
I'm trying to build a application that has different kinds of users, I'm using authlogic for user authentication.
因此,我有一个用户模型,该模型具有authlogic进行魔术的必填字段.现在,我想添加几个不同的模型,这些模型将描述针对不同类型用户的额外字段.
So I have one user model that has the required field for authlogic to do its magic. I now want to add a couple of different models that would describe the extra fields for the different kinds of users.
让我们说一个用户注册后,他将选择他的用户类型,完成注册后,他将能够添加特定于他的用户模型的信息.
Lets say that a user registers, he would then select his user type, when he is done registering he would be able to add information that is specific for his user model.
做到这一点的最佳方法是什么?我目前正在研究多态模型,但是我不确定这是最好的方法.任何帮助将不胜感激,谢谢.
What would be the best way to do this? I am currently looking into polymorphic models but I'm not sure that's the best route to take. Any help would be greatly appreciated, thanks.
推荐答案
您可以创建不同的profile
表,只需将配置文件与用户绑定即可.因此,对于每种用户类型,您可以创建一个表并在其中存储特定信息,并具有一个user_id
列以指向users
.
You can create different profile
tables and just tie the profile to the user. So for each user type you can create a table and store the specific info there and have a user_id
column to point back to users
.
class User < ActiveRecord::Base
has_one :type_1
has_one :type_2
end
class Type1 < ActiveRecord::Base
belongs_to :user
end
class Type2 < ActiveRecord::Base
belongs_to :user
end
现在这不是很干,如果您不断添加用户类型,可能会导致问题.因此,您可以研究多态性.
Now this isn't very DRY and could lead to problems if you are constantly adding user types. So you could look into polymorphism.
对于多态,users
表将定义用户是什么类型(profileable_id
和profileable_type
).像这样:
For polymorphism, the users
table would define what type the user is (profileable_id
and profileable_type
). So something like this:
class User < ActiveRecord::Base
belongs_to :profileable, :polymorphic => true
end
class Type1 < ActiveRecord::Base
has_one :user, :as => :profileable
end
class Type2 < ActiveRecord::Base
has_one :user, :as => :profileable
end
然后为用户类型提供STI(单表继承)的第三个选项.但是,如果用户类型字段之间的差异很大,那么扩展就不会很好.
Then there is a third option of STI (single table inheritance) for the user types. But that doesn't scale well if the user type fields differ dramatically.
这篇关于不同用户类型的Ruby on Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!