1
我User
模式是這樣的:Rails的SQL查詢共同的朋友
has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :followed_users, through: :relationships, source: :followed
has_many :reverse_relationships, foreign_key: "followed_id",
class_name: "Relationship",
dependent: :destroy
has_many :followers, through: :reverse_relationships, source: :follower
我要的是原始SQL查詢來獲取用戶,一個用戶遵循並通過遵循回來。
目前我只就得到了作爲獲得用戶的ID,我以下:
followed_user_ids = "SELECT followed_id FROM relationships
WHERE follower_id = #{user.id}"
我有一個返回共同的朋友一軌方法,但我想要的SQL相當於:
def mutual_friends
# interesect both arrays to find similar elements
self.followed_users & self.followers
end