Rails - friends of current_user with @user?

I am slowly introducing the ability to add and remove friends to a Rails application, but I find it difficult to change the Add Friend button to Remove Friend and vice versa depending on whether the current_user

friends are with a viewed profile @user

.

Here's what I have in my model user.rb

so far (courtesy of this answer to another question):

has_many :friendships
has_many :passive_friendships, :class_name => "Friendship", :foreign_key => "friend_id"

has_many :active_friends, -> { where(friendships: { approved: true}) }, :through => :friendships, :source => :friend
has_many :passive_friends, -> { where(friendships: { approved: true}) }, :through => :passive_friendships, :source => :user
has_many :pending_friends, -> { where(friendships: { approved: false}) }, :through => :friendships, :source => :friend
has_many :requested_friendships, -> { where(friendships: { approved: false}) }, :through => :passive_friendships, :source => :user

def friends
    active_friends | passive_friends
end

def friend_with?(user)
    # ... How would I go about this?
end

      

Any help would be greatly appreciated.

+3


source to share


1 answer


You can define friend_with?

like this:

def friend_with?(other_user)
  friendships.find_by(friend_id: other_user.id)
end

      



Then you can use current_user.friend_with? some_user

to confirm if the friends are two friends.

Hope it helps!

+3


source







All Articles