質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Q&A

解決済

1回答

2505閲覧

undefined method `each' for nil:NilClassのエラー

baseball1551

総合スコア16

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

0グッド

0クリップ

投稿2019/07/28 05:03

undefined method `each' for nil:NilClassgaが解決できない

画像投稿アプリを作成しております。
index画面に投稿一覧を表示する機能を実装後に以下のエラーメッセージが発生しました。

NoMethodError in Posts#index

undefined method `each' for nil:NilClass

<% @posts.each do |post| %> <div class="col-md-8 col-md-2 mx-auto"> <div class="card-wrap"> <div class="card"> <div class="card-header align-items-center d-flex">

該当のソースコード

index.html.erb <% @posts.each do |post| %> <div class="col-md-8 col-md-2 mx-auto"> <div class="card-wrap"> <div class="card"> <div class="card-header align-items-center d-flex"> <%= link_to user_path(post.user), class: "no-text-decoration" do %> <%= image_tag avatar_url(post.user), class: "post-profile-icon" %> <% end %> <%= link_to user_path(post.user), class: "black-color no-text-decoration", title: post.user.name do %> <strong><%= post.user.name %></strong> <% end %> <% if post.user_id == current_user.id %> <%= link_to post_path(post), method: :delete, class: "ml-auto mx-0 my-auto" do %> <div class="delete-post-icon"> </div> <% end %> <% end %> </div> <%= link_to(post_path(post)) do %> <%= image_tag post.photos.first.image.url(:medium), class: "card-img-top" %> <% end %> <div class="card-body"> <div class="row parts"> <div id="like-icon-post-<%= post.id.to_s %>"> <% if post.liked_by(current_user).present? %> <%= link_to "いいねを取り消す", post_like_path(post.id, post.liked_by(current_user)), method: :DELETE, remote: true, class: "loved hide-text" %> <% else %> <%= link_to "いいね", post_likes_path(post), method: :POST, remote: true, class: "love hide-text" %> <% end %> </div> <%= link_to "", "#", class: "comment" %> </div> <div id="like-text-post-<%= post.id.to_s %>"> <%= render "like_text", { likes: post.likes } %> </div> <div> <span><strong><%= post.user.name %></strong></span> <span><%= post.caption %></span> <%= link_to time_ago_in_words(post.created_at).upcase + "前", post_path(post), class: "post-time no-text-decoration" %> <div id="comment-post-<%= post.id.to_s %>"> <%= render 'comment_list', { post: post } %> </div> <%= link_to time_ago_in_words(post.created_at).upcase + "前", post_path(post), class: "light-color post-time no-text-decoration" %> <hr> <div class="row actions" id="comment-form-post-<%= post.id.to_s %>"> <%= form_with model: [post, Comment.new], class: "w-100" do |f| %> <%= f.hidden_field :user_id, value: current_user.id %> <%= f.hidden_field :post_id, value: post.id %> <%= f.text_field :comment, class: "form-control comment-input border-0", placeholder: "コメント ...", autocomplete: :off %> <% end %> </div> </div> </div> </div> </div> </div> <% end %>

posts_controller.rb

1class PostsController < ApplicationController 2 before_action :authenticate_user! 3 before_action :set_post, only: %i(show destroy) 4 5 def new 6 @post = Post.new 7 @post.photos.build 8 end 9 10 def create 11 @post = Post.new(post_params) 12 if @post.photos.present? 13 @post.save 14 redirect_to root_path 15 flash[:notice] = "投稿が保存されました" 16 else 17 redirect_to root_path 18 flash[:alert] = "投稿に失敗しました" 19 end 20 21 def index 22 # orderはデータベースから取り出す順序を指定 23 @posts = Post.limit(10).includes(:photos, :user).order('created_at DESC') 24 end 25 26 def show 27 end 28 29 def destroy 30 if @post.user == current_user 31 flash[:notice] = "投稿が削除されました。" if @post.destroy 32 else 33 flash[:alert] = "投稿の削除に失敗しました。" 34 end 35 redirect_to root_path 36 end 37 38 end 39 40 private 41 42 def post_params 43 # includes関連するテーブルをまとめて取得する 44 params.require(:post).permit(:caption, photos_attributes: [:image]).merge(user_id: current_user.id) 45 end 46 47 def set_post 48 @post = Post.find_by(id: params[:id]) 49 end 50end

routes.rb

1Rails.application.routes.draw do 2 devise_for :users, 3 controllers: { registrations: 'registrations' } 4 5 root 'posts#index' 6 7 get '/users/:id', to: 'users#show', as: 'user' 8 9 resources :posts, only: %i(new create index show destroy) do 10 resources :photos, only: %i(create) 11 resources :likes, only: %i(create destroy) 12 resources :comments, only: %i(create destroy) 13 end 14end

試したこと

・index.html.erbに<%# if @posts.present? %>を代入するとエラーは消えますが、投稿の一覧が反映されません。
なお、newページから新規投稿後indexページに移動した場合は投稿一覧が問題なく表示されます。

補足情報(FW/ツールのバージョンなど)

・以下Post.allです。
[1] pry(main)> Post.all
Post Load (4.2ms) SELECT "posts".* FROM "posts"
=> [#<Post:0x00007fbf82f14700
id: 1,
caption: "agaghagagagag",
user_id: 1,
created_at: Mon, 22 Jul 2019 13:50:47 UTC +00:00,
updated_at: Mon, 22 Jul 2019 13:50:47 UTC +00:00>,
<Post:0x00007fbf82f1b320
id: 2,
caption: "agaghagagagag",
user_id: 2,
created_at: Tue, 23 Jul 2019 13:18:52 UTC +00:00,
updated_at: Tue, 23 Jul 2019 13:18:52 UTC +00:00>,
<Post:0x00007fbf82f1b140
id: 4,
caption: "こんにちは",
user_id: 2,
created_at: Wed, 24 Jul 2019 13:37:26 UTC +00:00,
updated_at: Wed, 24 Jul 2019 13:37:26 UTC +00:00>,
:

ご教授いただければ幸いです。
何卒よろしくお願い致します。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

gouf

2019/07/28 05:46

エディタは何を利用されていますか? 「create」メソッド定義の中に入れ子になる形で ほかの index などのメソッドが定義されているように見受けられます
baseball1551

2019/07/28 06:10

ご指摘ありがとうございます。 入れ子はずしたら解決できました。凡ミスを見逃してました、、 因みにエディタはvscodeでした!
guest

回答1

0

自己解決

「index」が「create」メソッド定義の中の入れ子になってました。

投稿2019/07/28 07:04

baseball1551

総合スコア16

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問