1

说用户A被连接到B,然后用户B自动地认为与用户A连接如何使用rails ActiveRecord以最小的成本实现连接列表的概念?

Userhas_manyconnection

连接表:

id, user_id, connected_user_id


id || user_id|| connected_user_id

1 || 1 || 2

2 || 3 || 1

3 || 2 || 3



预期成果:

User.find(1).connections

[<用户ID:2,...>,<用户ID:3,...>]

User.find(2).connections

[<用户ID:1,.. >,<用户ID:3,...>]

回答

0

如果你需要一个多一对多的关系,它听起来像你这样做,你可以设置一个has_many through relationship

class User < ApplicationRecord 
    has_many :connections 
    has_many :connected_users, through: :connections 
end 

class Connection < ApplicationRecord 
    belongs_to :user 
    belongs_to :connected_user, class_name: "User" 
end 

然后找到所有连接像你愿意,你可以在你的用户类中创建一个方法:

def get_connections 
    User.find(Connection.where(user_id: self.id).connected_user_ids + Connection.where(connected_user_id: self.id).user_ids) 
end 

User.find(1).get_connections应该返回

[<用户ID:2。 ..>,<用户名:3,...>]

+0

why connecte用户表中将d_user_id作为参考? – Manish

+0

@处理您需要将connected_user_id列添加到您的用户表中,以作为对其他用户ID的引用。我使用示例迁移更新了我的答案。 – CChandler81

+0

您不认为这是不正确的方式吗?因为它会为同一用户的多个连接创建多个记录条目? – Manish