Don P
Don P

Reputation: 63778

If a record isn't found, make an attribute check return false instead of an error

I want to check two things:

  1. Has a user received a friend request? current_user.friend_requests.find_by_receiver_id(user.id)

  2. And if so, have they accepted it? current_user.friend_requests.find_by_receiver_id(user.id).accepted

The problem is #2 raises an error if no request existed. How can I avoid this, and simply have it return false?

Upvotes: 0

Views: 55

Answers (1)

Marek Lipka
Marek Lipka

Reputation: 51191

You can very easily return nil (which is falsy) if the record is not present, using ActiveSupport's try method:

current_user.friend_requests.find_by_receiver_id(user.id).try(:accepted)

Upvotes: 1

Related Questions