【问题标题】:ArgumentError (wrong number of arguments (given 2, expected 0..1)ArgumentError(参数数量错误(给定 2,预期 0..1)
【发布时间】:2021-05-12 21:39:19
【问题描述】:

我在用户模型中有这个功能

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)expected 0..1是什么意思?为什么给它2?

【问题讨论】:

  • 我猜Friendship.exists?(self.id,user_id) 给出了错误。除非你破坏了ActiveRecord::FinderMethods#exists?,否则它定义为exists?(conditions = :none)。这给出了 0..1 的数量,因为它有一个带有默认值的参数。当然,如果没有适当的堆栈跟踪,我们无法真正知道。 idownvotedbecau.se/noexceptiondetails
  • 这可能是stackoverflow.com/questions/37244283/…的副本(至少在精神上)
  • 我使用了 Rails 控制台,这就是为什么我不知道哪一行给出了这个错误。我将函数名称从存在更改? to requested_before 所以它不会与rails的内置功能混淆,所以现在可以工作了谢谢

标签: ruby-on-rails rails-activerecord


【解决方案1】:

存在吗?方法定义为:

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

这意味着,conditions 是该方法期望接收的唯一参数,并且您在调用它时传递了它self.id, user_id,两个参数self.iduser_id

要解决此问题,您必须决定使用哪个值来验证数据库中是否存在友谊记录。但不管它是什么,它应该是self.iduser_id 或任何其他,但只有一个。

【讨论】:

    【解决方案2】:

    您也可以这样做,在过滤后进行检查。

    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)
    

    【讨论】:

    • 您可以在exists? 上使用where 参数,它仍然是单个哈希参数。
    • 正确,但出于某种原因,我一直更喜欢这种方式。
    猜你喜欢
    • 1970-01-01
    • 2023-01-27
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多