Tony Beninate
Tony Beninate

Reputation: 1985

How to see if a record with doesn't already exist

I have a Friendship model which allows users to become friends with one another. The records for these Frienships has a requesting_user_id and an accepting_user_id. I want to build a method that checks to see that a record with the same accepting_user and requesting_user pair doesn't already exist. In short, that a one user has already befriended another user.

I started this in my User model:

def can_befriend?(accepting_user)
  @accepting_user = Friendship.find_by_accepting_user_id(accepting_user)
  @requesting_user = current_user
end

But I'm not sure how to check that the pair doesn't already exist. Any help?

Upvotes: 1

Views: 190

Answers (1)

trogdor33
trogdor33

Reputation: 175

You can actually use a dynamic cross-finder method that will search for both at the same time. It's a mouthful, but should work.

@old_friendship = Friendship.find_by_accepting_user_id_and_requesting_user_id(accepting_user.id, requesting_user.id)
if @old_friendship.nil?
    #create new friendship here
end

Upvotes: 2

Related Questions