I’m trying to create a hash with an array inside:
# 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 are methods for an external API (mite.yo.lk). They work and i get data back, so thats not the failure.
Unfortunately, i have to go this way, cause the API doesn’t have any methods to filter projects by the customer id.
That’s the error message:
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'
I don’t understand whats wrong here?
what @thorstenmüller said is correct. Looks like the Projects contains references to stale customers?
I would recommend defensive coding, provided it does not introduce logical errors. Something like:
Again, I would only recommend this if stale customers are acceptable in your database.
Another thing to look out for is that project.customer_id is a consistant type (i.e. always an Integer or String):
and
I have personally been caught out on this far too many times.
HTH and best.