ArgumentError(参数数量错误(给定 2,预期 0..1)
ArgumentError (wrong number of arguments (given 2, expected 0..1)
我在用户模型中有这个功能
def send_request(user_id)
unless Friendship.exists?(self.id,user_id)
Friendship.create(sender_id:self.id, receiver_id:user_id)
end
end
在 rails 控制台中 u1 = User.find(1)
然后 u1.send_request(2)
我看到 ArgumentError (wrong number of arguments (given 2, expected 0..1)
预期 0..1 的含义是什么?为什么给出 2?
存在吗?方法定义为:
def exists?(conditions = :none)
...
end
意思是,conditions
是该方法期望接收的唯一参数,并且你在调用它时传递了这个self.id, user_id
,两个参数,self.id
和user_id
.
要解决此问题,您必须决定要使用哪个值来验证数据库中是否存在 Friendship 记录。但不管它是什么,它应该是 self.id
、user_id
或任何其他,但只能是一个。
你也可以这样做,在过滤后进行检查。
if Friendship.where(sender_id: self.id, receiver_id: user_id).exists?
不过话又说回来你也可以使用
Friendship.find_or_create_by(sender_id: self.id, receiver_id: user_id)
我在用户模型中有这个功能
def send_request(user_id)
unless Friendship.exists?(self.id,user_id)
Friendship.create(sender_id:self.id, receiver_id:user_id)
end
end
在 rails 控制台中 u1 = User.find(1)
然后 u1.send_request(2)
我看到 ArgumentError (wrong number of arguments (given 2, expected 0..1)
预期 0..1 的含义是什么?为什么给出 2?
存在吗?方法定义为:
def exists?(conditions = :none)
...
end
意思是,conditions
是该方法期望接收的唯一参数,并且你在调用它时传递了这个self.id, user_id
,两个参数,self.id
和user_id
.
要解决此问题,您必须决定要使用哪个值来验证数据库中是否存在 Friendship 记录。但不管它是什么,它应该是 self.id
、user_id
或任何其他,但只能是一个。
你也可以这样做,在过滤后进行检查。
if Friendship.where(sender_id: self.id, receiver_id: user_id).exists?
不过话又说回来你也可以使用
Friendship.find_or_create_by(sender_id: self.id, receiver_id: user_id)