将值推入数组时,nil:NilClass 的未定义方法“[]”

2024-03-09

我正在尝试创建一个包含数组的哈希值:

# create new hash to store customers and their projects
@customers = Hash.new

# get all customers from Mite
Mite::Customer.all.each do |customer|
  @customers[customer.id] = {:name => customer.name, :projects => []}
end

# get all projects from Mite and store them in the :projects array
Mite::Project.all.each do |project|
  @customers[project.customer_id][:projects] << project # line 17
end

Mite::Project.all and Mite::Customer.all是外部 API (mite.yo.lk) 的方法。他们工作了,我得到了数据,所以这不是失败。

不幸的是,我必须走这条路,因为 API 没有任何方法可以按客户 ID 过滤项目。

这是错误消息:

undefined method `[]' for nil:NilClass

and

app/controllers/dashboard_controller.rb:17:in `block in index'
app/controllers/dashboard_controller.rb:16:in `each'
app/controllers/dashboard_controller.rb:16:in `index'

我不明白这里出了什么问题?


@thorstenmüller 所说的是正确的。看起来项目包含对过时客户的引用?

我会推荐防御性编码,只要它不会引入逻辑错误。就像是:

# get all projects from Mite and store them in the :projects array
Mite::Project.all.each do |project|
  if @customers[project.customer_id].present?
    @customers[project.customer_id] << project
  end
end

再次强调,只有当您的数据库中可以接受过时的客户时,我才会推荐这样做。

另一件需要注意的事情是 project.customer_id 是一致的类型(即始终是整数或字符串):

# get all customers from Mite
Mite::Customer.all.each do |customer|
  @customers[customer.id.to_i] = {:name => customer.name, :projects => []}
end

and

# get all projects from Mite and store them in the :projects array
Mite::Project.all.each do |project|
  @customers[project.customer_id.to_i][:projects] << project # line 17
end

我个人已经被这件事抓到太多次了。

HTH 和最好的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将值推入数组时,nil:NilClass 的未定义方法“[]” 的相关文章

随机推荐