前提・実現したいこと
NoMethodErrorを修正したいです。
Progateでは、Railsを使って、Twitterのようなアプリケーションを作ります。
これを、自身のMacのローカル環境で実践していました。
発生している問題・エラーメッセージ
app/views/posts/index.html.erbのページにて
undefined method `image_name' for nil:NilClass
=> 3行目と6行目にエラーができています。
<div class="main posts-index"> <div class="container"> <% @posts.each do |post| %> =>ここにエラー <div class="posts-index-item"> <div class="post-left"> <img src="<%= "/user_images/#{post.user.image_name}" %>"> =>ここにエラー </div> <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>

controller/post_controller.rbにて
class PostsController < ApplicationController before_action :authenticate_user before_action :ensure_correct_user, {only: [:edit, :update, :destroy]} def index @posts = Post.all.order(created_at: :desc) end def show @post = Post.find_by(id: params[:id]) @user = User.find_by(id: @post.user_id) end def new @post = Post.new end def create @post = Post.new( content: params[:content], user_id: @current_user.id ) if @post.save flash[:notice] = "Post successfully created" redirect_to("/posts/index") else render("posts/new") end 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] = "Post successfully edited" redirect_to("/posts/index") else render("posts/edit") end end def destroy @post = Post.find_by(id: params[:id]) @post.destroy flash[:notice] = "Post successfully deleted" redirect_to("/posts/index") end def ensure_correct_user @post = Post.find_by(id: params[:id]) if @post.user_id != @current_user.id flash[:notice] = "Unauthorized access" redirect_to("/posts/index") end end end
model/post.rbにて
class Post < ApplicationRecord validates :content, {presence: true, length: {maximum: 140}} validates :user_id, {presence: true} def users return User.find_by(id: self.user._id) end end
試したこと
Progateのコードを全てそのまま模写したり、時にはコピペをしました。
しかし、うまくいきませんでした。
テラテイル内でこれに似たエラーの解決方法を見つけ、実戦しましたが、これも上手くいきませんでした。
=>データベースが壊れているかもしれないので、データを削除してみる。
以下のようなエラーが出た時は、どこを修正すればいいのでしょうか…
undefined method `image_name' for nil:NilClass
回答2件
あなたの回答
tips
プレビュー