6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby on Railsで”undefined method `each' for nil:NilClass”エラーが出た時の対処法

Posted at

#環境・状況

#症状
構築した画面の動作確認にて下記エラー発生

NoMethodError in Tasks#index
Showing /home/ec2-user/environment/rails_projects/todo/app/views/tasks/index.html.erb where line #3 raised:

undefined method `each' for nil:NilClass
Extracted source (around line #3):             
1 <h1>ToDoアプリ</h1>
2 <ul>
3   <% @tasks.each do |task| %>
4     <li>
5       <%= check_box_tag '','' %>
6       <%= task.title %>
Rails.root: /home/ec2-user/environment/rails_projects/todo

エラー部分は

undefined method `each' for nil:NilClass

#原因
繰り返し処理の対象である@tasksの中身がnilである。

#解決策

コントローラーファイルであるTasks_controller.rb内のスペルミス

class TasksController < ApplicationController
  def index
    @taskes = Task.all
   ^^^^^^ ※”Tasks”ではなく”Taskes”とスペルミス。
  end
end

#参考
エラーfor nil:NilClassについて

nil(他の言語ではnullということも多い、「何もない」という特殊なオブジェクトです)に対してメソッドを実行しようとすると、表記のような「NilClassにメソッドがない」旨のエラーになります。

6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?