# User.already\_friend\_of(friend)?

**URL:** <https://www.ruby-forum.com/t/user-already-friend-of-friend/98063>\
**Category:** Rails\
**Created:** [January 27, 2006, 9:54pm UTC](https://www.ruby-forum.com/t/user-already-friend-of-friend/98063 "2006-01-27T21:54:09Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![i8ramin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/e36b37/32.png) [@i8ramin](https://www.ruby-forum.com/u/i8ramin)\
**Post date:** [January 27, 2006, 9:54pm UTC](https://www.ruby-forum.com/t/user-already-friend-of-friend/98063/1 "2006-01-27T21:54:09Z")

</div>

I have a User model who HBTM Friends (class User). I would like to check  
for the existance of a user in the friends table before actually adding  
them (in case they were already added as a friend.)

I have a method called already\_friend\_of?(friend) defined in my User  
model, but I am not sure how to define this method. I simply want to  
check to see if one user is already a friend of another user (I also use  
this method in my views to change the state of some links and buttons -  
for example, the ‘add friend’ button becomes ‘remove friend’.)

My method currently looks like this, but it doesn’t seem to be  
working…

def already\_friend\_of?(friend)  
begin  
self.friends.find(friend)  
true  
rescue  
false  
end  
end

I appreciate any hints you can give me regarding this matter.

Thank you,  
Ramin

---

<div class="post-metadata">

**Author:** ![i8ramin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/e36b37/32.png) [@i8ramin](https://www.ruby-forum.com/u/i8ramin)\
**Post date:** [January 27, 2006, 10:01pm UTC](https://www.ruby-forum.com/t/user-already-friend-of-friend/98063/2 "2006-01-27T22:01:57Z")

</div>

def already\_friend\_of?(friend)  
begin  
self.friends.find(friend.id)  
true  
rescue  
false  
end  
end

I think this is going to be very expensive because you’re calling this  
method on many pages (and more times per page). If you are just checking  
whether the current (logged in) user has this friend, you’d better  
create a method that gets a list of id’s from the database. These id’s  
are the id’s of her friends.

Then the check method will be:

def friend\_of?(friend)  
@friend\_ids.include?(friend.id)  
end

And you would need a method like load\_friend\_ids that populates the  
@friend\_ids array.

Jules

---

<div class="post-metadata">

**Author:** ![i8ramin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/e36b37/32.png) [@i8ramin](https://www.ruby-forum.com/u/i8ramin)\
**Post date:** [January 27, 2006, 10:45pm UTC](https://www.ruby-forum.com/t/user-already-friend-of-friend/98063/3 "2006-01-27T22:45:04Z")

</div>

Thank you Jules. I just forgot the .id part it seems.

I will also take your advice on using the array of id’s … i did feel  
like it was an expensive call, but wasn’t sure how to go about it.  
thanks again.
