Ruby on Rails下同一列中2个表之间的2个关系的问题
我有一个疑问,我正在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
自引用多对多结构通常称为物料清单。这是一个非常好的想法,并且在关系数据库中非常常用。这是数据模型。您将具有布尔属性,例如
IsAccepted
和IsRejected
。请勿将列命名为
user_id1, 2
。请使用真正有意义的名称,例如host_id
和guest_id
或requester_id
和friend_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
andIsRejected
.Please do not name the columns as
user_id1, 2
. Please call them something that is actually meaningful, suchhost_id
andguest_id
orrequester_id
andfriend_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.
实际上这里引用了非常相似的情况: http://oldwiki.rubyonrails.org/rails/pages /如何创建ASelfReferentialManyToManyRelationship
There is actually a very similar situation referenced here: http://oldwiki.rubyonrails.org/rails/pages/HowToCreateASelfReferentialManyToManyRelationship