My User
model looks like this:
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
What I want is the raw SQL query to get users that a given user follows and is followed back by.
Currently I've only gotten as far as getting the ids of users I'm following:
followed_user_ids = "SELECT followed_id FROM relationships
WHERE follower_id = #{user.id}"
I have a rails methods that returns mutual friends, but I want the SQL equivalent:
def mutual_friends
# interesect both arrays to find similar elements
self.followed_users & self.followers
end
Something like this should work
SELECT followed_id
FROM relationships
WHERE follower_id = #{user.id} AND followed_id IN (
SELECT follower_id FROM relationships WHERE followed_id = #{user.id}
)
Please use it like this, let me know if it works for you.
has_many :company_friendships, autosave: true
has_many :company_friends, through: :company_friendships, autosave: true
has_many :inverse_company_friendships, class_name: "CompanyFriendship", foreign_key: "company_friend_id", autosave: true
has_many :inverse_company_friends, through: :inverse_company_friendships, source: :company, autosave: true
def mutual_company_friends
Company.where(id: (company_friends | inverse_company_friends).map(&:id))
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.