Ruby on Rails下同一列中2个表之间的2个关系的问题

发布于 2024-10-20 21:20:03 字数 537 浏览 2 评论 0原文

我有一个疑问,我正在 Ruby on Rails 网站上创建一个朋友的平台;我有一个名为 users 的表和一个名为 friends 的表,用于管理用户之间的友谊。在朋友中,我有2个字段,*user_id1*和*user_id2*。这是我在模型中建立的关系:

class User < ActiveRecord::Base
    has_many :friends
end
class Friend < ActiveRecord::Base
    belongs_to :user, :foreign_key => "user_id1"
    belongs_to :user, :foreign_key => "user_id2"
end

这是处理这种情况的好方法吗?另一个想法是创建另一个模型,该模型指向数据库中的同一个表 userAux,并将其用于关系。你认为什么是最好的?你有更好的主意吗?

提前致谢。

I have a doubt, Im making a friend's platform on a Ruby on Rails site; I have a table called users, and a table called friends that manages the friendships between the users. In friends I have 2 fields, *user_id1* and *user_id2*. This is the relationship I made in the models:

class User < ActiveRecord::Base
    has_many :friends
end
class Friend < ActiveRecord::Base
    belongs_to :user, :foreign_key => "user_id1"
    belongs_to :user, :foreign_key => "user_id2"
end

Is this a good way to handle this situation? Another idea is create another model that points to the same table in the database, userAux, and use it for the relationship. What do you think is best? Do you have a better idea?

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

子栖 2024-10-27 21:20:03

自引用多对多结构通常称为物料清单。这是一个非常好的想法,并且在关系数据库中非常常用。这是数据模型。您将具有布尔属性,例如 IsAcceptedIsRejected

请勿将列命名为 user_id1, 2。请使用真正有意义的名称,例如 host_idguest_idrequester_idfriend_id。只有当您编码时,其相关性才会变得清晰。

不熟悉关系建模标准的读者可能会发现 IDEFIX符号很有用。

A self-referencing many-to-many structure is often called a Bill of Materials. It is a very good idea, and quite commonly used in Relational databases. Here is the Data Model. You would have boolean attributes such as IsAccepted and IsRejected.

Please do not name the columns as user_id1, 2. Please call them something that is actually meaningful, such host_id and guest_id or requester_id and friend_id. The relevance of that will only become clear when you are coding.

Readers who are unfamiliar with the Relational Modelling Standard may find IDEFIX Notation useful.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文