如何对实际具有字段的对象使用 Rails 多态?
假设我有一个用户模型,并且我想要拥有不同的用户角色。在单个应用程序中,您可以简单地将角色存储为字符串,或者存储为另一个模型,这很好。
但是如果您想为各个模型存储更多关联该怎么办?例如,假设管理员包含指向集合的链接并且属于许多普通用户不应关联的集合?事实上,其他用户将链接到管理员没有的一组完整的其他模型。
我们是否将所有关联都放在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我建议使用 Rails 单表继承。本质上,您的数据库中将有一个
users
表和一个根User
模型。多个模型(每个“角色”一个)可以从User
继承,并具有自己的关联:I would suggest using Rails Single Table Inheritance. Essentially, you'll have a
users
table in your database, and a rootUser
model. Multiple models (one for each "role") can inherit fromUser
, and have their own associations: