1

I have this function inside user model

def send_request(user_id)
    unless Friendship.exists?(self.id,user_id) 
      Friendship.create(sender_id:self.id, receiver_id:user_id)
    end
  end

In the rails console u1 = User.find(1) then u1.send_request(2) I see ArgumentError (wrong number of arguments (given 2, expected 0..1) What is the meaning of expected 0..1? and why it is given 2?

Eyeslandic
  • 14,553
  • 13
  • 41
  • 54
Bishoy Faheem
  • 37
  • 2
  • 9
  • I'm guessing `Friendship.exists?(self.id,user_id)` is giving the error. Unless you have clobbered [`ActiveRecord::FinderMethods#exists?`](https://api.rubyonrails.org/v6.1.3.1/classes/ActiveRecord/FinderMethods.html#method-i-exists-3F) its defined as `exists?(conditions = :none)`. That gives an arity of `0..1` as it has one argument with a default value. Of course we can't really know without a proper stack trace. https://idownvotedbecau.se/noexceptiondetails/ – max May 12 '21 at 21:44
  • This is a possible duplicate (at least in spirit) of https://stackoverflow.com/questions/37244283/how-to-model-a-mutual-friendship-in-rails – max May 12 '21 at 21:58
  • I used Rails console this is why I didn't know which line giving this error. I changed the function name from exists? to requested_before so It does not get confused with the built-in function of rails so It works now Thank you – Bishoy Faheem May 17 '21 at 12:37

2 Answers2

2

The exists? method is defined as:

def exists?(conditions = :none)
  ...
end

It means, conditions is the only argument the method is expecting to receive, and you have passed this when invoking it self.id, user_id, two arguments, self.id and user_id.

To fix the problem you have to decide which value you're going to use to validate if the Friendship record exists or not in your database. But whatever it is, it should be either self.id, user_id or any other, but just one.

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
1

You can also do this, doing the check after filtering.

if Friendship.where(sender_id: self.id, receiver_id: user_id).exists?

but then again you might just as well use

Friendship.find_or_create_by(sender_id: self.id, receiver_id: user_id)
Eyeslandic
  • 14,553
  • 13
  • 41
  • 54