Rails 关系建模
我有一个用户表和一个礼物表。用户可以为朋友挑选礼物。我正在考虑创建一个表来存储用户 ID 和礼物 ID,以跟踪哪个用户为谁挑选了哪个礼物。如何建模这种关系?我认为用户和礼物之间存在 HABTM 关系。是这样吗?
I have a users table and a gifts table. Users can pick gifts for their friends. I am thinking of creating a table to store user id and gift id to track which user picked which gift for whom. How to model this relation? I think users and gifts have a HABTM relation. Is that right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
现在可以进行以下调用:
确保在
user_gifts
中对user_id
、friend_id
、gift_id
列建立索引桌子。Try this:
Now following calls are possible:
Make sure you index the
user_id
,friend_id
,gift_id
columns inuser_gifts
table.好吧,首先它是一个三向关系,因为你有 Users -> 。朋友,还有用户->礼物。
我会使用 has_many :through 并将朋友的 ID 存储在那里。查询起来会有点尴尬,但应该可以。
Well, first of all it's a three-way relation, as you have Users -> Friends, as well as Users -> Gifts.
I would go with a has_many :through and store there the friend's ID. It will be a bit awkward to query, but it should work.