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

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

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

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

Q&A

解決済

1回答

394閲覧

rails5.2.2 掲示板の作成:コメントの投稿についてご教示お願いします!

Richard.K

総合スコア2

Ruby on Rails 5

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

0グッド

0クリップ

投稿2020/12/02 08:07

実現したいこと

railsで掲示板を作っています。topics/showページ内に一対多の関係のcommentsを新規投稿と投稿の一覧を表示しようとしています。
AWS Cloud9 を使用しています。どなた様かご教示お願いできましたら幸甚です。

発生している問題・エラーメッセージ

NoMethodError in Comments#create Showing /app/views/topics/show.html.erb where line #6 raised: undefined method `user' for nil:NilClass

リンク内容(エラーがおきた行です)

該当のソースコード

class CommentsController < ApplicationController before_action :require_user_logged_in before_action :correct_user, only: [:destroy] def create @comment = current_user.comments.build(comment_params) if @comment.save flash[:success] = 'コメントを投稿しました。' redirect_to root_url else @comments = current_user.comments.order(id: :asc) flash.now[:danger] = 'コメントの投稿に失敗しました。' render 'topics/show' end end private def comment_params params.require(:comment).permit(:content) end def correct_user @comment = current_user.comments.find_by(id: params[:id]) unless @comment redirect_to root_url end end end
class TopicsController < ApplicationController before_action :require_user_logged_in before_action :correct_user, only: [:destroy] def show @topic = Topic.find(params[:id]) @comment = current_user.comments.build @comments = @topic.comments.order(id: :asc) end private # Strong Parameter def topic_params params.require(:topic).permit(:title, :condition, :content) end def correct_user @topic = current_user.topics.find_by(id: params[:id]) unless @topic redirect_to root_url end end end

topics/show

<div class="text-right"> <% if current_user == @topic.user %> <%= link_to "編集する", edit_topic_path(@topic), class: 'btn btn-danger w-150px' %> <% end %> </div> <table class="table table-bordered table-striped container mt-3"> <tr> <th class="text-center" colspan="2">タイトル</th> <th class="text-center">募集人</th> <th class="text-center">状態</th> </tr> <tr> <td class="text-center" colspan="2"><%= @topic.title %></td> <td class="text-center"><%= @topic.user.name %></td> <td class="text-center"><%= @topic.condition ? "募集中" : "終了" %></td> </tr> <tr> <th class="text-center">投稿日</th> <td class="text-center"><%= l @topic.created_at, format: :year %></td> <th class="text-center">編集日時</th> <td class="text-center"><%= l @topic.updated_at, format: :short %></td> </tr> <tr> <td class="text-center" colspan="4"><%= @topic.content %></td> </tr> </table> <%= render 'comments/show', comments: @comments %> <h5><strong>質問する コメント投稿欄</strong></h5> <%= form_with(model: @comment, local: true) do |f| %> <div class="form-group row"> <div class="col-12"> <%= f.text_area :content, size: '10x5', class: 'form-control', placeholder: '※投稿にはユーザ登録、ログインが必要です。 250文字以内で投稿をお願いします。' %> </div> </div> <div class="text-right"> <%= f.submit '投稿する', class: 'btn btn-danger w-150px' %> </div> <% end %>

追加、必要な箇所がありましたら申し付けください。

試したこと

binding.pryを試しました。が手に負えません。

From: /app/controllers/comments_controller.rb:9 CommentsController#create: 6: def create 7: @comment = current_user.comments.build(comment_params) 8: binding.pry => 9: if @comment.save 10: flash[:success] = 'コメントを投稿しました。' 11: redirect_to root_url 12: else 13: @comments = current_user.comments.order(id: :asc) 14: flash.now[:danger] = 'コメントの投稿に失敗しました。' 15: render 'topics/show' 16: end 17: end [1] pry(#<CommentsController>)> params => <ActionController::Parameters {"utf8"=>"✓", "authenticity_token"=>"VHMQPFEw==", "comment"=><ActionController::Parameters {"content"=>"comments"} permitted: false>, "commit"=>"投稿する", "controller"=>"comments", "action"=>"create"} permitted: false> [2] pry(#<CommentsController>)> comment_params => <ActionController::Parameters {"content"=>"comments"} permitted: true> [3] pry(#<CommentsController>)> @comment => #<Comment:0x00007f75cc0d8e48 id: nil, content: "comments", user_id: 1, topic_id: nil, created_at: nil, updated_at: nil> [4] pry(#<CommentsController>)> next (0.9ms) BEGIN ↳ app/controllers/comments_controller.rb:9 (0.6ms) ROLLBACK ↳ app/controllers/comments_controller.rb:9 From: /app/controllers/comments_controller.rb:13 CommentsController#create:

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

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

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

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

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

guest

回答1

0

ベストアンサー

CommentsControllerのcreateで失敗すると render 'topics/show' となっています。
Topicsのshow.htmlでは<% if current_user == @topic.user %> と@topicが呼ばれています。しかしcreateでは@topicを用意していないのでこのエラーになります。
modelのcodeがないので推定ですが、Commentはbelongs_to topic ですよね?
comment_paramsにはcontentだけでtopic_idがないのでsaveに失敗しています。
createへtopic_idが渡るようにし、それを使ってcreateすると共に、失敗した時は @topicを作ってshowを呼んでください

投稿2020/12/02 09:12

winterboum

総合スコア23329

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

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

Richard.K

2020/12/26 09:45 編集

winterboum 様 ご回答ありがとうございます! class Comment は belongs_to :topicです。 申し訳ありません、普通ならわかりやすいご説明で解決! なのでしょうが、如何せん理解が足りていません。 追加の質問をお願いできますと幸いです。 Strong Parameterは params.permit(:content, :topic_id) でよろしいでしょうか? def create には @topic = comment.topic.find(params[:id]) ではなさそうだしと頭を悩ませています。 よろしくお願いいたします。
winterboum

2020/12/02 13:29

そこを呼び出すviewを載せてください
Richard.K

2020/12/26 09:44

投稿できるようになりました、ありがとうございます! routes.rb resources :topics do resources :comments end comments_Controller def create @topic = Topic.find(params[:topic_id]) @comment = @topic.comments.create(comment_params) @comment.user = current_user @comment.save redirect_to topic_path(@topic) end
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問