如何对实际具有字段的对象使用 Rails 多态?

发布于 2024-11-06 08:36:49 字数 302 浏览 0 评论 0原文

假设我有一个用户模型,并且我想要拥有不同的用户角色。在单个应用程序中,您可以简单地将角色存储为字符串,或者存储为另一个模型,这很好。

但是如果您想为各个模型存储更多关联该怎么办?例如,假设管理员包含指向集合的链接并且属于许多普通用户不应关联的集合?事实上,其他用户将链接到管理员没有的一组完整的其他模型。

我们是否将所有关联都放在 User 对象中,然后根据用户的类型忽略它们?或者我们是否开始对 User 进行子类化(就像在 Hibernate 中一样)以仅包含该用户类型的关联和模型逻辑?

在 Rails 中执行此操作的方法是什么?谢谢!

Let's say I have a User model and I want to have different user roles. In a single application, you can simple store the role a string, or as another model and that's fine.

But what if you want to store more associations for the individual models? For example, let's say Admins contain links to collections and belongs to many collections that regular users should not be associated to? In fact, other users will be linked to a whole other set of models that Admins do not have.

Do we put all of the associations in the User object and just ignore them based on the type of the user? Or do we start subclassing User (like in Hibernate) to only contain the associations and model logic for that user type?

What is the way to do this in rails? Thanks!

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

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

发布评论

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

评论(1

若能看破又如何 2024-11-13 08:36:49

我建议使用 Rails 单表继承。本质上,您的数据库中将有一个users 表和一个根User 模型。多个模型(每个“角色”一个)可以从 User 继承,并具有自己的关联:

# Regular users have no associations
class User < ActiveRecord::Base
end

# Admins have collections and notes
class Admin < User
  has_many :collections
  has_many :notes
end

# Editors only have notes
class Editor < User
  has_many :notes
end

I would suggest using Rails Single Table Inheritance. Essentially, you'll have a users table in your database, and a root User model. Multiple models (one for each "role") can inherit from User, and have their own associations:

# Regular users have no associations
class User < ActiveRecord::Base
end

# Admins have collections and notes
class Admin < User
  has_many :collections
  has_many :notes
end

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