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

发布于 2024-08-28 05:38:50 字数 239 浏览 9 评论 0原文

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

因此,我有一个用户模型,它具有 authlogic 发挥其魔力所需的字段。我现在想添加几个不同的模型来描述不同类型用户的额外字段。

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

最好的方法是什么?我目前正在研究多态模型,但我不确定这是最好的路线。任何帮助将不胜感激,谢谢。

I'm trying to build a application that has different kinds of users, I'm using authlogic for user authentication.

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

安人多梦 2024-09-04 05:38:50

您可以创建不同的个人资料表,并将个人资料与用户联系起来。因此,对于每种用户类型,您可以创建一个表并在其中存储特定信息,并使用 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

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

对于多态性,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

然后针对用户类型有第三个选项 STI(单表继承)。但如果用户类型字段差异很大,那么这种方法就无法很好地扩展。

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.

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文