antonyCas
antonyCas

Reputation: 81

Ruby method expecting wrong number of arguments

I found some strange behaviour with a method I wrote in Ruby. When I call the method with two arguments the console says that it was expecting 0..1 but when I pass one argument it says it's expecting two. Can anyone explain to me why?

class Friendship < ApplicationRecord
    belongs_to :user
    belongs_to :friend, :class_name => "User"

    def self.request(user,friend)
        unless user == friend or Friendship.exists?(user,friend)
            transaction do
                create(:user => user, :friend => friend, :status => 'pending')
                create(:user => friend, :friend => user, :status => 'requested')
            end
        end
    end

    def self.accept(user,friend)
        transaction do
            accepted_at = Time.now
            accept_one_side(user,friend,accepted_at)
            accept_one_side(friend,user,accepted_at)
        end
    end

    def self.accept_one_side(user,friend,accepted_at)
        request = find_by_user_id_and_friend_id(user,friend)
        request.status = 'accepted'
        request.accepted_at = accepted_at
        request.save!
    end
end

It is the request method I am calling in the console like so:

Friendship.request(user1,user2)

where user1 and user2 are the first and second users in my database.

Upvotes: 0

Views: 341

Answers (1)

spickermann
spickermann

Reputation: 106782

It is Friendship.exists?(user,friend) that raises the error. exists? is a finder method that takes only one argument.

Instead you will need to write something like this:

Friendship.exists?(user_id: user.id, friend_id: friend.id)

Upvotes: 2

Related Questions