假设用户 A 连接到 B,则用户 B 自动被视为连接到用户 A。
用户
has_many
连接
连接表:
id, user_id, connected_user_id
说
编号 ||用户名|| connected_user_id
1 || 1 || 2
2 || 3 || 1
3 || 2 || 3
预期结果:
User.find(1).connections
[< User id:2, ... >,< User id:3, ... > ]
User.find(2).connections
[< User id:1, ... >, < User id:3, ... >]
最佳答案
如果你需要一个多对多的关系,你可以设置一个 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
应该返回
[< User id:2, ... >,< User id:3, ... > ]
关于mysql - 如何使用 rails ActiveRecord 以最小的成本实现连接列表的概念?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45114625/