前提・実現したいこと
railsでSNSのようなサイトを作成しておりますが、
投稿一覧画面でユーザー名を表示したいのですがうまくいかないです。
発生している問題・エラーメッセージ
NoMethodError in Posts#index undefined method `name' for nil:NilClass <div class="post-right"> <div class="post-user-name"> <%= link_to(post.user.name,"/users/#{post.user.id}") %> </div> <%= link_to(post.content, "/posts/#{post.id}",) %> </div>
index.html.erb
<div class="main posts-index"> <div class="row"> <% @posts.each do |post| %> <div class="posts-index-item col-md-6 col-xs-12"> <div class="post-right"> <div class="post-user-name"> <%= link_to(post.user.name,"/users/#{post.user.id}") %> </div> <%= link_to(post.content, "/posts/#{post.id}",) %> </div> </div> <% end %> </div> </div>
post_controller.rb
class PostsController < ApplicationController before_action :authenticate_user, only: [:new, :show, :edit] def index @posts = Post.all.order(created_at: :desc) end def show @post = Post.find_by(id: params[:id]) @user = @post.user @favorite = current_user.favorites.find_by(post_id: @post.id) @favorites_count = Favorite.where(post_id: @post.id).count end def new @post = Post.new end def create @post = Post.new(content: params[:content],user_id: @current_user.id) @post.user_id = current_user.id if params[:back] render :new return end unless @post.valid? render :new return end if params[:send] @post.save flash[:notice] = "投稿を作成しました" redirect_to posts_path return end render :confirm end def edit @post = Post.find_by(id: params[:id]) end def update @post = Post.find_by(id: params[:id]) @post.content = params[:content] if @post.save flash[:notice] = "投稿を編集しました" redirect_to posts_path else render :edit end end def destroy @post = Post.find_by(id: params[:id]) @post.destroy flash[:notice] = "投稿を削除しました" redirect_to posts_path end def confirm @post = Post.new(params[:post]) if @post.invalid? render :confirm else render :posts end end def ensure_correct_user @post = Post.find_by(id: params[:id]) if @post.user_id != @current_user.id flash[:notice] = "投稿者が削除できます" redirect_to posts_path end end end
よろしくお願いいたします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。