简体   繁体   中英

Ruby: undefined method `[]=' for nil:NilClass

Sorry for my poor English. I got the error like below.

undefined method `[]=' for nil:NilClass

app/controllers/tasks_controller.rb:69:in `block in show'
app/controllers/tasks_controller.rb:67:in `each'
app/controllers/tasks_controller.rb:67:in `each_with_index'
app/controllers/tasks_controller.rb:67:in `show'

Here is the code in 'tasks_controller.rb':

@teammates_form = Array.new(@teammates.size-1){Hash.new}
@teammates.each_with_index do |t, idx|
  if t.id != current_user.id
    @teammates_form[idx]['id'] = t.id  # <--- line 69
    @teammates_form[idx]['name'] = t.name
    @teammates_form[idx]['t_id'] = @task.id
  end
end

But if I change codes like:

@teammates_form[0]['id'] = t.id
@teammates_form[0]['name'] = t.name
@teammates_form[0]['t_id'] = @task.id

It works... I don't know why I can't use index in array.

Thanks in advance for any help.

Have you checked to see which time through the loop the error happens using something like Pry?

I suspect that actually it is on the last time that the error is happening. On the first line of your code you create an array of hashes using Array.new(@teammates.size-1){Hash.new} . This means that if @teammates contains 3 items, your new array will only contain 2 hashes (ie [{}, {}] ). This in turn means that for the final team mate, @teammates_form[idx] will be nil. Try using Array.new(@teammates.size){Hash.new} instead and see if that helps.

#                                          ⇓⇓  ? WHY?
@teammates_form = Array.new(@teammates.size-1){Hash.new}

You yield this error on the last iteration on @teammates , since @teammates_form is 1 element shorter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM