错误的参数数量(给定0,预期1) - Ruby

时间:2017-03-22 10:10:22

标签: ruby-on-rails ruby

在我的用户模型中,我有这段代码:

def job_amount(user)
  parent = Parent.where(parents: {firstname: user.firstname, name: user.name})
  demands = Demand.where(parent_id: parent.pluck(:id))
  demands.sum(:quantity)
end

称之为:

<%= @user.job_amount.to_s %>

引发以下错误:

wrong number of arguments (given 0, expected 1)

任何想法为什么?

2 个答案:

答案 0 :(得分:2)

这是更好的

def job_amount
  parent = Parent.where(parents: {firstname: firstname, name: name})
  demands = Demand.where(parent_id: parent.pluck(:id))
  demands.sum(:quantity)
end

答案 1 :(得分:1)

  

错误的参数数量(给定0,预期为1)

这意味着该方法需要一个参数,但是你传递零

<%= @user.job_amount(@user).to_s %>

虽然,这是非常糟糕的

如果job_amountUser模型中的实例方法,则您不需要发送@user作为参数,您可以使用self

问题: job_amount(user)方法的位置是什么?

修改

将方法更改为此还可以解决问题

def job_amount
  parent = Parent.where(parents: {firstname: firstname, name: name})
  demands = Demand.where(parent_id: parent.pluck(:id))
  demands.sum(:quantity)
end

<%= @user.job_amount.to_s %>