前提・実現したいこと
show.html.erb画面へ投稿画面を表示させたいです。
ここに質問の内容を詳しく書いてください。
発生している問題・エラーメッセージ
nilClassにメソッドがない
エラーメッセージ
NoMethodError in Users#show
undefined method `image?' for nil:NilClass
該当のソースコード
ソースコード
●app/views/users/show.html.erb
<h1>投稿一覧</h1> <ul> <% @posts.each do |post| %> <li> <% if @post.image? %> <%= image_tag @post.thumb.url %> <% else %> <%= image_tag 'noimage.gif' %> <% end %> <%= link_to post.image, image_url %> <%= link_to post.shop_name, post %>: <%= congestion_values[post.congestion] %> <%= link_to '投稿を編集する', edit_post_path(post) %> <%= link_to '投稿を削除する', post, method: :delete, data: { confirm: '本当に削除してよろしいですか?' } %> </li> <% end %> </ul> <div class="row"> <aside class="col-xs-4"> <div class="panel-heading"> <h3 class="panel-title"><%= @user.name %></h3> </div> <div class="panel-body"> <img class="media-object img-rounded img-responsive" src="<%= gravatar_url(@user, { size: 500}) %>" alt=""> </div> <%= link_to '混み具合を報告', new_post_path %> </aside> <!--<div class="col-xs-8">--> <!-- <ul class="nav nav-tabs nav-justified">--> <!-- <li><a href="#">自分の投稿</a></li>--> <!-- <#%= link_to '投稿を編集する', edit_post_path(@post) %>--> <!-- <%#= link_to '投稿を削除する', @post, method: :delete, data: { confirm: '本当に削除してよろしいですか?' } %>--> <!-- </ul>--> <!--</div>--> </div>●app/posts/posts_controllers.rb
class PostsController < ApplicationController
before_action :require_user_logged_in
before_action :correct_user, only: [:destroy]
def show
@post = Post.find(params[:id])
end
def new
@post = Post.new
end
def create
@post = current_user.posts.build(post_params)
if @post.save
flash[:success] = 'メッセージを投稿しました'
redirect_to root_url
else
@posts = current_user.posts.order('created_at DESC').page(params[:page])
flash.now[:danger] = '投稿に失敗しました'
render 'toppages/index'
end
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update(post_params) flash[:success] = '投稿が更新されました' redirect_to @post else flash.now[:danger] = '投稿が更新されませんでした' render :edit end
end
def destroy
@post.destroy
flash[:success] = 'メッセージを削除しました'
redirect_back(fallback_location: root_path)
end
private
def post_params
params.require(:post).permit(:congestion, :shop_name, :image)
end
def correct_user
@post = current_user.posts.find_by(id: params[:id])
unless
redirect_to root_url
end
end
end
補足情報(FW/ツールのバージョンなど)
宜しくお願いします。
あなたの回答
tips
プレビュー