LoginSignup
0
1

More than 3 years have passed since last update.

postした内容が一覧で表示できなかった時のエラー解決

Posted at

Ruby on railsで投稿アプリを作りたい。
その際に、userとpostモデルのある状態をまず作ろうと思ったのですが、一ついくらメンターに相談しても時間がかかったエラーがありました。

ActionView::Template::Error (undefined method `each' for nil:NilClass)

postコントローラでindexアクションに

def index   
  @posts = Post.all.order(id: :asc)
end

投稿したpostの内容を一覧表示にするところで、

index.html.erbに渡します

 <% @posts.each do |post| %>   
    <%= post.title %>
    <%= post.content %>
  <% end %>

これで表示できるはずが、
ActionView::Template::Error (undefined method `each' for nil:NilClass)
エラーでググっても、出てくるものは@postsがnilになってるので、、とか
同じ様なエラーでも@posts@post になってたり、全角スペースが入っていたり、、

ルーティングもOK
DBに保存もできている
showページは表示できるので、投稿自体は渡っている。

なぜ?

原因

postコントローラーのメソッドの書き順が原因でした。

index
new
create
show
edit
update
destoy

と書くのが普通なところを
new
create
index←ここ

とindexメソッドをnewとcreateの後に書いていたのが原因だった様です。
1日悩んで、メンターさんに相談してもなかなか進まなかったよ〜言うなれば根本的な部分だったのかも。
でも、いろんな原因を探るうちに理解できた部分も多かったのでエラーは成長には欠かせないのかもしれません。

0
1
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
0
1