Rails 多级用户数据库设计
我有一个用户数据库表,其中包含常见字段,例如密码、电子邮件等。还有一个名为level
的字段,它定义用户级别,例如成员< /em>、编辑或管理员。
还有一些特定于成员、编辑和管理员的字段,而其他人则不需要。所以我认为我应该为用户类型创建单独的表。
问题就在这里; 如果我想遵循Rails的方式,我应该如何解决这个问题?无论是在数据库设计还是关联方面。
I have a database table for users which contains common fields like password, email etc. And there is also a field named level
which defines user level such as member, editor or admin.
There is also some fields that specific for members, editors and admins which others don't need. So I think I should create separated tables for user types.
And here's the problem; how should I approach this problem if I want to follow Rails way? Both in terms of database design and associations.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
似乎您正在寻找基于角色的授权系统,以及每个角色的特定属性。实现此目的的一种方法是使用如下所示的数据模型:
这样,您可以确保如果从用户中删除该角色(通过级联删除),则与该特定角色相关的所有属性都将被删除。
不过,您必须确保所有属性模型都强制执行如下验证规则:
如果您的用户只能拥有一个角色,您可以通过在模型上添加一个
role
字段来简化这一过程,然后相应地为可选属性(属于
用户)编写验证规则。尽管如此,前一种模式为未来的调整提供了更大的潜力(创建新角色只是创造新记录)。不过我不是这方面的专家,所以你也可以继续寻找灵感; declarative_authorization gem 提供了对其数据模型的解释,您可能也会觉得有趣:
seems you are looking for a role-based authorization system, coupled with specific attributes for each role. One way to achieve this would be with a data model looking like this :
this way, you ensure that all attributes related to a specific role are deleted if that role is removed from the user (by cascade delete).
You will have, though, to ensure that all your attributes models enforce validation rules like this :
if your user can only have one role, you can simplify this by adding a
role
field on the model, and then write validation rules on optional attributes (thatbelong_to
a user) accordingly. Still,the former model offers more potential for future adjustments (creating a new role is just creating a new record).I'm not an expert on this matter though, so you can also continue to seek out inspiration ; the declarative_authorization gem provides an explanation of its data model that you may find interesting, too: