Rails 中具有相同键的两个表而不是 has_one 关系
我正在开发 Rail 网络应用程序。我有两个模型,用户,其中包含非常基本的信息:id、用户名和密码,以及个人资料,其中包括每个用户的个人资料。 (主要原因是有一个轻量级的用户模型,将定期调用,以及一个成熟的配置文件,将不定期调用)。每个模型都有很多子模型。
现在,我有一个具有自己主键的 Profile,然后是一个与 User 匹配的外键 user_id。
但是,我想知道我是否应该拥有与 User 模型具有相同键的 Profile 模型(即,如果记录引用同一用户,则 Profile.id == User.id )。这很方便,因为当我有一个属于 User 的对象时,我希望它属于 Profile,反之亦然。例如,我可以指定 User has_many 和 Spec has_many 与 ChildModel 的关系。因为它们使用相同的密钥,所以我不必将 ChildModel 合并到 Spec,然后将 Profile 合并到 User 来找出与子对象关联的用户。
缺点是在未来,如果由于某种原因我的 User 和 Spec 的主键之间存在差异,那么我就会遇到很大的麻烦。
对于这种情况,您有什么建议?
谢谢。
I am working on a Rail webapp. I have two models, User, which contains very basic information: id, username and password, and Profile, which includes profile for each user. (The main reason is to have a lightweight User model, which will be called regularly, and a full-fledged profile which will be called irregularly). Each of these models has many children.
Right now, I have Profile with its own primary key, then a foreign key user_id to match with User.
However, I wonder if I should have Profile model with the same key as User model (i.e., Profile.id == User.id if the records refer to the same user). This is convenience because when I have an object that belongs to User, I want it to belong to Profile and vise versa. For example, I can specify User has_many and Spec has_many relationship to ChildModel. Because they use the same key, I don't have to merge ChildModel to Spec, then Profile to User to find out user associated with child object.
The downside is in the future, if for some reason I have discrepancy between primary key of User and Spec, then I am in deep trouble.
What would be your recommendation for this situation?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来您应该在
Profile
和User
之间使用一对一的关系。您可以使用has_one
和belongs_to
声明来创建它。正如使用 Rails 进行敏捷 Web 开发第四版中所述:
It sounds like you should be using a one-to-one relationship between
Profile
andUser
. You can create this using thehas_one
andbelongs_to
declarations.As stated in Agile Web Development with Rails Fourth Edition:
我建议您使用 has_one 关系映射,例如以下
用户类
迁移
I would suggest you to use has_one relation mapping like following
user class
migrations