简体   繁体   English

在轨道上与红宝石建立对称关系的最佳方法是什么?

[英]What is the best way to model a symmetric relation with ruby on rails?

I am looking for an elegant way to model a symmetric relation (like friendship between users) in rails (though this may be more of a general database question). 我正在寻找一种在Rails中建模对称关系 (如用户之间的友谊)的优雅方法(尽管这可能更像是一个一般的数据库问题)。 I know of several approaches, but none seem elegant: 我知道几种方法,但似乎都不太优雅:

  1. Create a user_user relation table with foreign keys of the users. 用用户的外键创建一个user_user关系表。 I don't like it since it is essentially an asymmetric solution. 我不喜欢它,因为它本质上是一个非对称解决方案。 I saw an approach that forces the user with the lower id into the first column and the other into the second column, and query the relation from both ends using union. 我看到了一种方法,该方法将具有较低ID的用户强制进入第一列,而另一用户强制进入第二列,并使用union从两端查询关系。 This feels like a hack. 感觉就像是骇客。

  2. Create a friendship table, where each row represent a relation, and: 创建一个友谊表,其中每一行代表一个关系,并且:

    • For one-to-one: add a column to the users table to reference the relation 一对一:在用户表中添加一列以引用该关系
    • For many-to-many: add a user_friendship table that will hold a foreign key to the users and friendships tables. 对于多对多:添加一个user_friendship表,该表将为用户和友谊表保留一个外键。

    The problem with this approach is that is seems cumbersome and also that nothing enforces that the friendship will be shared exactly by 2 users. 这种方法的问题在于,它看起来很麻烦,而且也没有任何东西可以强制2个用户完全共享友谊。

I hope that there's a more elegant solution than these. 我希望有比这些更好的解决方案。 any ideas? 有任何想法吗?

I would create a model Friendship that holds the foreign keys of the users who are friends you can make a validation which ensures that there is only one friendship with the same users simply by doing something like: 我将创建一个模型Friendship,其中包含可以进行验证的朋友用户的外键,以确保仅通过执行以下操作即可与同一用户建立一个朋友关系:

validates :friend_id, :uniqueness => { :scope => :user_id }

In my opinion this is a very elegant solution which provides a lot of flexibillity. 我认为这是一个非常优雅的解决方案,具有很大的灵活性。 Checkout the has_one :through association in the rails guide A Guide to Active Record Associations if you want to model something like a friendship. 检出HAS_ONE:通过在轨协会指导指南活动记录关联 ,如果你要像友谊建模。

Of course there is also the has_and_belongs_to_many association. 当然,还有has_and_belongs_to_many关联。 But it does not provide as much flexibillity as if you create a model and thus usually is not such a good idea. 但是,它提供的灵活性不如创建模型那样灵活,因此通常不是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM