簡體   English   中英

如何使用Rails ActiveRecord以最小的成本實現連接列表的概念?

[英]How to achieve concept of connection list with minimal cost using rails ActiveRecord?

假設用戶A連接到B,則用戶B被自動認為與用戶A連接。

User has_many connection

連接表:

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,...>]

如果您需要一個多對多關系(聽起來像您這樣做),則可以通過關系建立has_many

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

然后,根據需要查找所有連接,可以在User類中創建一個方法:

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,...>,<用戶ID:3,...>]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM