Ruby on rails具有不同的用户类型

Pal*_*der 1 ruby-on-rails polymorphic-associations

我正在尝试构建一个具有不同类型用户的应用程序,我正在使用authlogic进行用户身份验证.

所以我有一个用户模型,其中包含authlogic所需的字段以实现其魔力.我现在想要添加几个不同的模型来描述不同类型用户的额外字段.

假设用户注册,然后他会选择他的用户类型,当他完成注册时,他将能够添加特定于他的用户模型的信息.

最好的方法是什么?我目前正在研究多态模型,但我不确定这是最好的选择.非常感谢任何帮助,谢谢.

Ton*_*not 6

您可以创建不同的profile表,只需将配置文件绑定到用户即可.因此,对于每种用户类型,您可以创建一个表并在其中存储特定信息,并user_id指向一个列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
Run Code Online (Sandbox Code Playgroud)

现在这不是很干,如果你不断添加用户类型,可能会导致问题.所以你可以研究多态性.

对于多态性,该users表将定义用户的类型(profileable_idprofileable_type).所以像这样:

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
Run Code Online (Sandbox Code Playgroud)

然后是用户类型的第三个STI选项(单表继承).但是,如果用户类型字段显着不同,则无法很好地扩展.