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

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

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

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

Ruby on Rails 6

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

Ruby on Rails

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

Q&A

2回答

1006閲覧

ruby on rails コメント一覧から他のユーザーページに飛ぶ時にエラー

takaaki919

総合スコア2

Ruby

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

Ruby on Rails 6

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

Ruby on Rails

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

0グッド

0クリップ

投稿2020/10/11 08:19

コメント一覧から他のユーザーページに飛ぼうとした時にこのエラーが出ました。
調べても分からなかったので教えて頂きたいです。イメージ説明
イメージ説明

NoMethodError in PostsController#show undefined method `user' for nil:NilClass Did you mean? super

該当のソースコード

posts.cotroller.rb

1class PostsController < ApplicationController 2 before_action :authenticate_user 3 before_action :ensure_correct_user, {only: [:edit, :update, :destroy]} 4 5 def index 6 @posts = Post.all.order(created_at: :desc) 7 end 8 9 def show 10 @post = Post.find_by(id: params[:id]) 11 @user = @post.user ←ここがエラーになりました 12 @post = Post.find(params[:id])  13 @comments = @post.comments 14 @comment = @comments.new 15 end 16 def new 17 @post = Post.new 18 end 19 20 def create 21 @post = Post.new( 22 content: params[:content], 23 user_id: @current_user.id 24 ) 25 if @post.save 26 flash[:notice] = "投稿を作成しました" 27 redirect_to("/posts/index") 28 else 29 render("posts/new") 30 end 31 end 32 33 def edit 34 @post = Post.find_by(id: params[:id]) 35 end 36 37 def update 38 @post = Post.find_by(id: params[:id]) 39 @post.content = params[:content] 40 if @post.save 41 flash[:notice] = "投稿を編集しました" 42 redirect_to("/posts/index") 43 else 44 render("posts/edit") 45 end 46 end 47 48 def destroy 49 @post = Post.find_by(id: params[:id]) 50 @post.destroy 51 flash[:notice] = "投稿を削除しました" 52 redirect_to("/posts/index") 53 end 54 55 def ensure_correct_user 56 @post = Post.find_by(id: params[:id]) 57 if @post.user_id != @current_user.id 58 flash[:notice] = "権限がありません" 59 redirect_to("/posts/index") 60 end 61 end 62 63end

comments.controller.rb

1class CommentsController < ApplicationController 2 3 before_action :authenticate_user 4 5 def create 6 logger.debug "*"*100 7 logger.debug "[comments_controller.rb]" 8 logger.debug "*"*100 9 post = Post.find(params[:post_id]) 10 @comment = post.comments.build(comment_params) 11 @comment.user_id = current_user.id 12 if @comment.save 13 logger.debug "saved" 14 flash[:success] = "コメントしました" 15 redirect_to(post) 16 else 17 logger.debug "failed" 18 flash[:success] = "コメントできませんでした" 19 redirect_to(post) 20 end 21 end 22 23 private 24 25 def comment_params 26 params.require(:comment).permit(:content) 27 end 28 logger.debug "*"*100 29end

posts/show.htmi.erb

viwe/posts/show.html.erb

1<div class="main posts-show"> 2 <div class="container"> 3 <div class="posts-show-item"> 4 <div class="post-user-name"> 5 <img src="<%= "/user_images/#{@user.image_name}" %>"> ←ここがエラー 6 <%= link_to(@user.name, "/users/#{@user.id}") %> 7 </div> 8 <p> 9 <%= @post.content %> 10 </p> 11 12 <div class="post-time"> 13 <%= @post.created_at %> 14 </div> 15 <% if @post.user_id == @current_user.id %> 16 <div class="post-menus"> 17 <%= link_to("編集", "/posts/#{@post.id}/edit") %> 18 <%= link_to("削除", "/posts/#{@post.id}/destroy", {method: "post"}) %> 19 </div> 20 <% end %> 21 22<div class="comment-wrapper border-top mb-10"> 23 <p class="mt-5">コメント一覧</p> 24 <% @comments.each do |c| %> 25 <div> 26 <% unless c.user.blank? %> 27 <a href="<%= (c.user_id) %>"> 28 <img src="<%= "/user_images/#{c.user.image_name}" %>"></a> 29 <% end %> 30 <%= c.user.name unless c.user.blank? %> 31 <br /> 32 <%= c.content %> 33 </div> 34 <br /> 35 <% end %> 36 <% if user_signed_in? %> 37 <%= form_with(model: @comment, url: comments_path, method: :post, local: true) do |f| %> 38 <%= hidden_field_tag :post_id, @post.id %> 39 <%= f.text_area :content, class: "form-control", rows: 5 %> 40 <%= button_tag type: "submit", class: "btn btn-success float-right mt-1" do %> 41 <i class="far fa-comments"></i> コメントする 42 <% end %> 43 <% end %> 44 <% end %> 45</div> 46 </div> 47 48 </div> 49 50</div>

routes.rb

1Rails.application.routes.draw do 2 3 devise_for :users 4 get "login" => "users#login_form" 5 6 7 post "login" => "users#login" 8 post "logout" => "users#logout" 9 10 11 post "users/:id/update" => "users#update" 12 get "users/:id/edit" => "users#edit" 13 post "users/create" => "users#create" 14 get "singnup" => "users#new" 15 get "users/index" => "users#index" 16 get "users/:id" => "users#show", as: :user 17 18 get "posts/index" => "posts#index" 19 get "posts/new" => "posts#new" 20 get "posts/:id" => "posts#show", as: :post 21 22 resources :comments, only: [:create] 23 24 25 post "posts/create" => "posts#create" 26 27 get "posts/:id/edit" => "posts#edit" 28 29 post "posts/:id/update" => "posts#update" 30 post "posts/:id/destroy" => "posts#destroy" 31 get "/" => "home#top" 32 get "about" => "home#about" 33 34end

migrate/comments.rb

1class CreateComments < ActiveRecord::Migration[6.0] 2 def change 3 create_table :comments do |t| 4 t.string :content 5 t.references :user, null: false, foreign_key: true 6 t.references :post, null: false, foreign_key: true 7 8 t.timestamps 9 end 10 end 11end

users_controller.rb

1class UsersController < ApplicationController 2 3 before_action :authenticate_user, {only: [:index, :show, :edit, :update]} 4 before_action :forbid_login_user, {only: [:new, :create, :login_form, :login]} 5 before_action :ensure_correct_user, {only: [:edit, :update]} 6 7 8 def index 9 @users = User.all 10 end 11 12 def show 13 @user = User.find_by(id: params[:id]) 14 end 15 16 def new 17 @user = User.new 18 end 19 20 def create 21 @user = User.new( 22 name: params[:name], 23 email: params[:email], 24 image_name: "fashion-985556_1920.jpg", 25 password: params[:password] 26 ) 27 if @user.save 28 session[:user_id] = @user.id 29 flash[:notice] = "ユーザー登録が完了しました" 30 redirect_to("/users/#{@user.id}") 31 else 32 render("users/new") 33 end 34 35 end 36 37 def edit 38 @user = User.find_by(id: params[:id]) 39 end 40 41 def update 42 @user = User.find_by(id: params[:id]) 43 @user.name = params[:name] 44 @user.email = params[:email] 45 46 if params[:image] 47 @user.image_name = "#{@user.id}.jpg" 48 image = params[:image] 49 File.binwrite("public/user_images/#{@user.image_name}", image.read) 50 end 51 52 if @user.save 53 flash[:notice] = "ユーザー情報を編集しました" 54 redirect_to("/users/#{@user.id}") 55 else 56 render("users/edit") 57 end 58 end 59 60 def login_from 61 end 62 63 64 def login 65 @user = User.find_by(email: params[:email]) 66 if @user && @user.valid_password?(params[:password]) 67 session[:user_id] = @user.id 68 flash[:notice] = "ログインしました" 69 redirect_to("/posts/index") 70 else 71 @error_message = "メールアドレスまたはパスワードが間違っています" 72 @email = params[:email] 73 @password = params[:password] 74 render("users/login_form") 75 end 76 end 77 78 def auth_failure 79 @user = User.new 80 render("users/login_form") 81 end 82 83 def logout 84 session[:user_id] = nil 85 flash[:notice] = "ログアウトしました" 86 redirect_to("/login") 87 end 88 89 def ensure_correct_user 90 if @current_user.id != params[:id].to_i 91 flash[:notice] = "権限がありません" 92 redirect_to("/posts/index") 93 end 94 end 95 96 97end

model/comment.rb

1class Comment < ApplicationRecord 2 belongs_to :user 3 belongs_to :post 4end

model/post.rb

1class Post < ApplicationRecord 2 3 validates :content, {presence: true, length: {maximum: 140}} 4 validates :user_id, {presence: true} 5 has_many :comments 6 7 def user 8 return User.find_by(id: self.user_id) 9 end 10 11end

model/user.rb

1class User < ApplicationRecord 2 # Include default devise modules. Others available are: 3 # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable 4 devise :database_authenticatable, :registerable, 5 :recoverable, :rememberable, :validatable 6 7 validates :name, {presence: true} 8 validates :email, {presence: true, uniqueness: true} 9 has_many :comments 10 11 def posts 12 return Post.where(user_id: self.id) 13 end 14 end``` 15

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

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

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

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

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

guest

回答2

0

イメージ説明
追加しましたが同じエラーです。

投稿2020/10/11 09:34

takaaki919

総合スコア2

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

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

gouf

2020/10/11 12:44

rails server の再起動は実施済みですか? その状況でも変化は見られませんか?
takaaki919

2020/10/11 13:02

再起動しましたが変わらずです。
guest

0

多分、PostモデルとUserモデルが繋がってないんだと思います。

Post.rbに

belongs_to :user

と書いてください

投稿2020/10/11 08:57

yamada_yuuki

総合スコア100

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

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

takaaki919

2020/10/11 09:41

追加しましたがエラーは変わらずです。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問