在 Rails 中转换模型(单表继承)
假设我有两种类型的用户:A
和 B
。 B
类型的用户拥有较少的权限,对字段的验证也不太严格(更多可以留空)。除此之外,它们与 A
类型基本相同。这个事实使我倾向于使用单表继承。
这是我担心的问题 - B
类型的用户可以升级到 A
类型。当他们升级时,他们应该保留所有相关记录。是否有一种简单的方法可以使用 STI 从一种模型类型转换为另一种模型类型,以便保留所有关联?你能举一个简单的例子吗?
Let's say I have two types of users, A
and B
. Users of type B
have fewer privileges and less-strict validations on fields (more can be blank). Otherwise, they're basically the same as type A
. This fact makes me inclined to use single table inheritance.
Here's my concern - type B
users can upgrade to type A
. When they upgrade, they should keep all their associated records. Is there an easy way to convert from one model type to another using STI such that all associations are preserved? Can you give a simple example?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要做的就是确保您在
type
列中给出了正确的值。将用户B升级为用户A时,只需将
type
属性中存储的值更改为用户A的类名即可。
例如:
将兼职人员升级为职员等级。
所有关联应保持不变。因为你只有一张实际的sql表。
PartTimeStaff 和 Staff 类的所有属性都保存在同一个表中。
请参阅 Rails API 和 单表继承
谢谢
All you need to do is make sure you have given the correct value in
type
column.While upgrading User B to User A, just change the value stored in
type
attribute to User A'sclass name.
Eg:
it will upgrade the part time staff to staff class.
All associations should be remain unchanged. Since you only have one actual sql table.
All the attributes for PartTimeStaff and Staff class are kept in the same table.
See more details from Rails API and Single Table Inheritance
thanks
也许您可以只有一个带有类型字段的用户模型,并且验证取决于类型。
Maybe you can have just one User model with a type field, and validations depend on the type.