Interacting Friends as an ActiveRecord Arel Relationship

I have the following models for my user:

class User < ActiveRecord::Base
  has_many :facebook_friendships
  has_many :facebook_friends, :through => :facebook_friendships, :source => :friend

  def mutual_facebook_friends_with(user)
    User.find_by_sql ["SELECT users.* FROM facebook_friendships AS a
                        INNER JOIN facebook_friendships AS b
                          ON a.user_id = ? AND b.user_id = ? AND a.friend_id = b.friend_id
                        INNER JOIN users ON users.id = a.friend_id", self.id, user.id]
  end

end

class FacebookFriendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => 'User'
end

If user ID 53 and user ID 97 are friends with each other, you will have the rows [53, 97] and [97, 53] in the facebook_friendships table in the database. Here is the raw sql query that I came up with to make mutual friends:

SELECT users.* FROM facebook_friendships AS a
  INNER JOIN facebook_friendships AS b
    ON a.user_id = :user_a AND b.user_id = :user_b AND a.friend_id = b.friend_id
  INNER JOIN users ON users.id = a.friend_id

I would mutually_other_with return a relation instead of an array. Thus, I could associate the result with other conditions, for example, where (college: "NYU") and get all the benefits of ActiveRecord. Is there a good way to do this?

+3
source share
2 answers

Have you tried #find_by_sql?

http://guides.rubyonrails.org/active_record_querying.html#finding-by-sql

SQL , find_by_sql. find_by_sql , . , :

 Client.find_by_sql("SELECT * FROM clients 
                     INNER JOIN orders ON clients.id = orders.client_id   
                     ORDER clients.created_at desc")

find_by_sql .

0

, , .

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
0

All Articles