前提・実現したいこと
Rails コメント機能の実装中です。
新着投稿画面から、詳細画面に飛び、そこでコメントと、コメント一覧の表示をさせたいです。
コメントまではできるのですが、コメント一覧がカラの配列になっていました。
そこDB検索をしたところ、post_id :nilとなっており、ここが問題であると考えています。
この問題がわかる方、教えていただきたいです。
該当のソースコード
postコントローラ show.html.erb
<P>投稿詳細ページ</P> <h3><%= @post.title%></h3> <h3><%= @post.content%></h3> <h2>コメント一覧</h2> <%= @comments.each do |c| %> <div> <%= @post.user.id %> <%= c.user.email %> <%= c.comment %> </div> <% end %> <%= form_with(model: [@post, @comment], local: true) do |f| %> <%= f.text_field :comment %> <%= f.submit "コメントする", class: "btn btn-primary" %> <% end %> <%= link_to "ホームへ戻る", posts_path %>
class CommentsController < ApplicationController def create @comment = Comment.new (comment_params) @comment.user_id = current_user.id if @comment.save redirect_back(fallback_location: root_path) else redirect_back(fallback_location: root_path) end end end private def comment_params params.require(:comment).permit(:comment) end
class PostsController < ApplicationController def index @search = Post.search(params[:q]) @post = @search.result @posts = Post.order(id: :desc).page(params[:page]).per(10) end def show @post = Post.find(params[:id]) @comments = @post.comments @comment = Comment.new end
[#<Comment id: 1, comment: "ありがとう", user_id: 14, post_id: nil, created_at: "2019-08-23 05:01:02", updated_at: "2019-08-23 05:01:02">
回答4件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。